Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:recycle: Declare streaming and raw HTTP response contracts https://github.com/siyuan-note/siyuan/issues/19378

Daniel42377592925d
diff --git a/app/src/types/api/index.d.ts b/app/src/types/api/index.d.ts
index 3d81648018..a2b4eae00c 100644
--- a/app/src/types/api/index.d.ts
+++ b/app/src/types/api/index.d.ts
@@ -3760,7 +3760,7 @@ export type APICallbackResponse<R> = R extends {code: infer C extends number}
type APIDirectCallbackResponse<R> = R extends {code: number} ? APICallbackResponse<R> : R;
type APIPostTail<C extends APIContract> = [
- cb?: (response: C extends {output: "binary"} ? JSONValue : C extends {output: "directJSON"} ? APIDirectCallbackResponse<C["response"]> | (C extends {noContent: true} ? "" : never) : APICallbackResponse<C["response"]>) => void,
+ cb?: (response: C extends {output: "binary"} ? JSONValue : C extends {output: "directJSON"} ? APIDirectCallbackResponse<C["response"]> | (C extends {noContent: true} ? "" : never) : C extends {output: "sse"} ? string | APICallbackResponse<C["response"]> : APICallbackResponse<C["response"]>) => void,
headers?: Record<string, string>,
failCallback?: (response: APIFetchFailure) => void,
signal?: AbortSignal,
diff --git a/docs/API-CONTRACTS.md b/docs/API-CONTRACTS.md
index ed2d340569..ca0b823208 100644
--- a/docs/API-CONTRACTS.md
+++ b/docs/API-CONTRACTS.md
@@ -86,6 +86,10 @@ Storage contracts keep arbitrary JSON limited to storage values; keys, recent do
## Multipart requests
+SSE endpoints declare each event name and payload with `SSEOptions` and `SSEEvent`. `StreamSSE` executes the existing stream lifecycle within the request; cancellation and cleanup remain inside that lifecycle. HTTP validation distinguishes `text/event-stream` from the declared pre-stream JSON failures, while `ValidateSSEEvent` checks each JSON event payload separately. Generated metadata exposes the event types; buffered fetch helpers still return the complete stream as text.
+
+Page responses use `HTTPContentOptions` to declare permitted HTTP status and media-type pairs and `SuccessHTTPContent` to preserve their bytes. This uses the existing binary transport and keeps JSON middleware errors separate. `FastJSON` preserves selected large responses' accelerated JSON encoder without changing their typed payloads or response envelope; encoding failures retain the standard encoder fallback.
+
`WebSocketOutput` uses `WebSocketOptions` to declare incoming and outgoing message types and the plugin admission failure status. `UpgradeWebSocket` hands the response writer to the connection lifecycle from `contractHandler`; `RejectWebSocket` serializes the declared rejection payload. Generated route metadata includes both message schemas, and `ValidateWebSocketMessage` validates frames separately from handshake responses and middleware envelopes. Handshake validation checks HTTP status and body; network regression tests verify upgrade headers, Origin rejection, message exchange, and cancellation.
Optional `*string` form fields preserve omission separately from an explicit empty string; use `nonnullable` because multipart text fields cannot contain JSON null. Import handlers use this distinction for defaults and delayed field validation. Upload progress starts before multipart parsing, and parse failures clear it before responding; Gin's cached form is reused for typed binding.
diff --git a/docs/API-CONTRACTS.zh-CN.md b/docs/API-CONTRACTS.zh-CN.md
index 1d0dd84791..2000851476 100644
--- a/docs/API-CONTRACTS.zh-CN.md
+++ b/docs/API-CONTRACTS.zh-CN.md
@@ -88,6 +88,10 @@ SQL 查询契约保留成功信封顶层的 `limit` 和 `truncated`。`SuccessSQ
## 文件上传请求
+SSE 接口通过 `SSEOptions` 和 `SSEEvent` 声明各事件名称及载荷。`StreamSSE` 在请求上下文内执行原有流生命周期,取消与清理仍在该生命周期内完成。HTTP 校验区分 `text/event-stream` 与声明过的流建立前 JSON 错误,`ValidateSSEEvent` 单独校验各事件的 JSON 载荷。生成声明包含事件类型;缓冲式 fetch 辅助函数仍将完整流作为文本返回。
+
+页面响应通过 `HTTPContentOptions` 声明允许的 HTTP 状态与媒体类型组合,通过 `SuccessHTTPContent` 保留原始字节,复用既有二进制传输并单独处理 JSON 中间件错误。`FastJSON` 为指定的大体量响应保留快速 JSON 编码,不改变有类型载荷及响应信封;编码失败时仍回退到标准编码器。
+
可选的 `*string` 表单字段区分未传字段与显式空字符串,并使用 `nonnullable`,因为表单文本不能包含 JSON 空值。导入处理器据此保留默认值和延后校验的行为。上传进度在解析表单前启动,解析失败时先清理进度再返回;类型绑定复用 Gin 缓存的表单。
`BinaryOutput` 通过 `BinaryContent` 和 `SuccessBinary` 声明原始文件响应。适配器保留字节和媒体类型,`ErrorStatus` 声明 JSON 失败响应使用的独立 HTTP 状态(`getFile` 使用 202)。schema 记录二进制成功响应和类型化 JSON 错误;`ValidateHTTPResponse` 先检查状态和媒体类型,再验证错误信封。生成的路由响应使用 `Blob`,现有 fetch 函数则使用 `JSONValue`,因为它们保留将文件内容解析为文本或 JSON 的行为。JSON 文件内容可以是任意 JSON,但结构化错误契约不因此放宽。
diff --git a/kernel/api/contract.go b/kernel/api/contract.go
index 29baa52a1f..6c1d88c6a4 100644
--- a/kernel/api/contract.go
+++ b/kernel/api/contract.go
@@ -7,6 +7,7 @@ import (
"github.com/88250/gulu"
"github.com/gin-gonic/gin"
+ goccyJSON "github.com/goccy/go-json"
"github.com/siyuan-note/siyuan/kernel/apicontract"
"github.com/siyuan-note/siyuan/kernel/conf"
"github.com/siyuan-note/siyuan/kernel/model"
@@ -42,11 +43,18 @@ func contractHandler[Request, Data any](endpoint apicontract.Endpoint[Request, D
handler func(*gin.Context, Request) apicontract.Response[Data], beforeDecode ...func(*gin.Context) *apicontract.Response[Data]) gin.HandlerFunc {
return func(c *gin.Context) {
writeResponse := func(response apicontract.Response[Data]) {
+ if after := response.AfterWrite(); after != nil {
+ defer after()
+ }
status := endpoint.Status(response)
if upgrade := response.Upgrade(); upgrade != nil {
upgrade(c.Writer, c.Request)
return
}
+ if stream := response.Stream(); stream != nil {
+ stream(c.Writer, c.Request)
+ return
+ }
if status == 204 {
c.Status(status)
return
@@ -55,6 +63,12 @@ func contractHandler[Request, Data any](endpoint apicontract.Endpoint[Request, D
c.Data(status, content.ContentType, content.Bytes)
return
}
+ if endpoint.Definition().FastJSON {
+ if data, err := response.MarshalWith(goccyJSON.Marshal); err == nil && len(data) > 0 {
+ c.Data(status, "application/json; charset=utf-8", data)
+ return
+ }
+ }
c.JSON(status, response)
}
// 保留在读取请求体前完成的角色判断或大小限制,提前响应也使用相同的载荷类型。
diff --git a/kernel/apicontract/contracts.go b/kernel/apicontract/contracts.go
index 73d1ac10f9..9e4acb2334 100644
--- a/kernel/apicontract/contracts.go
+++ b/kernel/apicontract/contracts.go
@@ -40,6 +40,9 @@ type Definition struct {
ErrorStatus int
NoContent bool
WebSocket *WebSocketDefinition
+ SSE *SSEDefinition
+ ContentVariants []HTTPContentVariant
+ FastJSON bool
AdditionalErrorStatuses []int
}
@@ -58,6 +61,9 @@ type ResponseOptions struct {
ErrorStatus int
NoContent bool
WebSocket *WebSocketDefinition
+ SSE *SSEDefinition
+ ContentVariants []HTTPContentVariant
+ FastJSON bool
AdditionalErrorStatuses []int
}
@@ -112,8 +118,8 @@ func define[Request, Data any](name, path string, body BodyMode, response Respon
d := Definition{Name: name, Path: path, Methods: methods, Body: body,
Request: reflect.TypeFor[Request](), Data: reflect.TypeFor[Data](),
ErrorCodes: append([]int{-1}, response.AdditionalCodes...), ErrorText: response.Text, DataNonNullable: response.NonNullable, DataOnError: response.DataOnError,
- Output: response.Output, ErrorStatus: response.ErrorStatus, NoContent: response.NoContent, WebSocket: response.WebSocket,
- AdditionalErrorStatuses: append([]int(nil), response.AdditionalErrorStatuses...)}
+ Output: response.Output, ErrorStatus: response.ErrorStatus, NoContent: response.NoContent, WebSocket: response.WebSocket, SSE: response.SSE,
+ AdditionalErrorStatuses: append([]int(nil), response.AdditionalErrorStatuses...), ContentVariants: append([]HTTPContentVariant(nil), response.ContentVariants...), FastJSON: response.FastJSON}
definitions = append(definitions, d)
return Endpoint[Request, Data]{definition: d}
}
@@ -501,60 +507,105 @@ var GetFile = define[FilePathRequest, BinaryContent]("getFile", "/api/file/getFi
var QuerySQL = define[SQLQueryRequest, SQLRows]("SQL", "/api/query/sql", JSONBody, ResponseOptions{AdditionalCodes: []int{1}, NonNullable: true}, "POST")
var RenderSprig = define[RenderSprigRequest, string]("renderSprig", "/api/template/renderSprig", JSONBody, ResponseOptions{}, "POST")
+
var GetDocSaveAsTemplateInfo = define[TemplateDocumentRequest, TemplateDocumentInfo]("getDocSaveAsTemplateInfo", "/api/template/getDocSaveAsTemplateInfo", JSONBody, ResponseOptions{}, "POST")
+
var DocSaveAsTemplate = define[SaveTemplateRequest, Null]("docSaveAsTemplate", "/api/template/docSaveAsTemplate", JSONBody, ResponseOptions{AdditionalCodes: []int{1}}, "POST")
+
var RenderTemplate = define[RenderTemplateRequest, RenderTemplateData]("renderTemplate", "/api/template/render", JSONBody, ResponseOptions{}, "POST")
+
var ManageTemplateFiles = define[TemplateFileRequest, TemplateManagementData]("manageTemplateFiles", "/api/template/manage", StructJSONBody, ResponseOptions{}, "POST")
var ResetGraph = define[EmptyRequest, ResetGraphData]("resetGraph", "/api/graph/resetGraph", NoBody, ResponseOptions{}, "POST")
+
var ResetLocalGraph = define[EmptyRequest, ResetLocalGraphData]("resetLocalGraph", "/api/graph/resetLocalGraph", NoBody, ResponseOptions{}, "POST")
+
var SetGraphConf = define[SetGraphConfRequest, GraphConfigurationData]("setGraphConf", "/api/graph/setGraphConf", JSONBody, ResponseOptions{}, "POST")
+
var GetGraph = define[GlobalGraphRequest, GlobalGraphData]("getGraph", "/api/graph/getGraph", JSONBody, ResponseOptions{DataOnError: true}, "POST")
+
var GetLocalGraph = define[LocalGraphRequest, LocalGraphData]("getLocalGraph", "/api/graph/getLocalGraph", JSONBody, ResponseOptions{DataOnError: true}, "POST")
var RefreshBacklink = define[RefreshBacklinkRequest, Null]("refreshBacklink", "/api/ref/refreshBacklink", JSONBody, ResponseOptions{}, "POST")
+
var GetBackmentionDoc = define[BackmentionDocumentRequest, BacklinkContextData]("getBackmentionDoc", "/api/ref/getBackmentionDoc", JSONBody, ResponseOptions{AdditionalCodes: []int{1}}, "POST")
+
var GetBacklinkDoc = define[BacklinkDocumentRequest, BacklinkContextData]("getBacklinkDoc", "/api/ref/getBacklinkDoc", JSONBody, ResponseOptions{AdditionalCodes: []int{1}}, "POST")
+
var GetBacklink2 = define[BacklinkListRequest, BacklinkListData]("getBacklink2", "/api/ref/getBacklink2", JSONBody, ResponseOptions{AdditionalCodes: []int{1}, DataOnError: true}, "POST")
var ContinueImportSY = define[ContinueImportSYRequest, ImportDocumentData]("continueImportSY", "/api/import/continueImportSY", JSONBody, ResponseOptions{}, "POST")
+
var CancelImportSY = define[ImportTokenRequest, Null]("cancelImportSY", "/api/import/cancelImportSY", JSONBody, ResponseOptions{}, "POST")
+
var StartObsidianVaultAnalysis = define[ObsidianAnalysisRequest, *ObsidianVaultTask]("startObsidianVaultAnalysis", "/api/import/startObsidianVaultAnalysis", JSONBody, ResponseOptions{}, "POST")
+
var GetObsidianVaultTask = define[ObsidianTaskRequest, *ObsidianVaultTask]("getObsidianVaultTask", "/api/import/getObsidianVaultTask", JSONBody, ResponseOptions{}, "POST")
+
var StartObsidianVaultImport = define[ObsidianImportRequest, *ObsidianVaultTask]("startObsidianVaultImport", "/api/import/startObsidianVaultImport", JSONBody, ResponseOptions{}, "POST")
+
var CancelObsidianVaultTask = define[ObsidianTaskRequest, *ObsidianVaultTask]("cancelObsidianVaultTask", "/api/import/cancelObsidianVaultTask", JSONBody, ResponseOptions{DataOnError: true}, "POST")
+
var ImportStdMd = define[ImportMarkdownRequest, Null]("importStdMd", "/api/import/importStdMd", JSONBody, ResponseOptions{}, "POST")
+
var ImportData = define[ImportDataRequest, Null]("importData", "/api/import/importData", MultipartBody, ResponseOptions{}, "POST")
+
var ImportZipMd = define[ImportZipMarkdownRequest, Null]("importZipMd", "/api/import/importZipMd", MultipartBody, ResponseOptions{}, "POST")
+
var ImportSY = define[ImportSYRequest, Null]("importSY", "/api/import/importSY", MultipartBody, ResponseOptions{}, "POST")
+
var ImportSYNotebook = define[ImportDataRequest, ImportNotebookData]("importSYNotebook", "/api/import/importSYNotebook", MultipartBody, ResponseOptions{}, "POST")
+
var ImportSYAuto = define[ImportSYRequest, ImportAutoData]("importSYAuto", "/api/import/importSYAuto", MultipartBody, ResponseOptions{DataOnError: true}, "POST")
var GetHistoryItems = define[HistoryItemsRequest, HistoryItemsData]("getHistoryItems", "/api/history/getHistoryItems", JSONBody, ResponseOptions{}, "POST")
+
var GetNotebookHistory = define[EmptyRequest, NotebookHistoryData]("getNotebookHistory", "/api/history/getNotebookHistory", NoBody, ResponseOptions{}, "POST")
+
var GetDocHistoryContent = define[DocHistoryContentRequest, DocHistoryContentData]("getDocHistoryContent", "/api/history/getDocHistoryContent", JSONBody, ResponseOptions{}, "POST")
+
var CreateDocHistory = define[CreateDocHistoryRequest, Null]("createDocHistory", "/api/history/createDocHistory", JSONBody, ResponseOptions{}, "POST")
+
var CreateAssetHistory = define[CreateAssetHistoryRequest, Null]("createAssetHistory", "/api/history/createAssetHistory", JSONBody, ResponseOptions{}, "POST")
+
var RollbackDocHistory = define[HistoryPathRequest, Null]("rollbackDocHistory", "/api/history/rollbackDocHistory", JSONBody, ResponseOptions{}, "POST")
+
var RollbackAssetsHistory = define[HistoryPathRequest, Null]("rollbackAssetsHistory", "/api/history/rollbackAssetsHistory", JSONBody, ResponseOptions{}, "POST")
+
var RollbackNotebookHistory = define[HistoryPathRequest, Null]("rollbackNotebookHistory", "/api/history/rollbackNotebookHistory", JSONBody, ResponseOptions{}, "POST")
+
var RollbackAttributeViewHistory = define[HistoryPathRequest, Null]("rollbackAttributeViewHistory", "/api/history/rollbackAttributeViewHistory", JSONBody, ResponseOptions{}, "POST")
+
var DiffDocVersions = define[DiffDocVersionsRequest, *DocVersionDiffResult]("diffDocVersions", "/api/history/diffDocVersions", JSONBody, ResponseOptions{}, "POST")
var SearchAssetByName = define[SearchAssetRequest, []*SearchAsset]("searchAsset", "/api/search/searchAsset", JSONBody, ResponseOptions{}, "POST")
+
var SearchWidget = define[SearchKeywordRequest, SearchWidgetData]("searchWidget", "/api/search/searchWidget", JSONBody, ResponseOptions{}, "POST")
+
var SearchTemplate = define[SearchKeywordRequest, SearchTemplateData]("searchTemplate", "/api/search/searchTemplate", JSONBody, ResponseOptions{}, "POST")
+
var RemoveSearchTemplate = define[SearchPathRequest, Null]("removeTemplate", "/api/search/removeTemplate", JSONBody, ResponseOptions{}, "POST")
+
var GetAssetContent = define[AssetContentRequest, AssetContentData]("getAssetContent", "/api/search/getAssetContent", JSONBody, ResponseOptions{}, "POST")
+
var GetAssetContentByPath = define[SearchPathRequest, AssetContentData]("getAssetContentByPath", "/api/search/getAssetContentByPath", JSONBody, ResponseOptions{}, "POST")
+
var ListInvalidBlockRefs = define[SearchPageRequest, SearchBlocksData]("listInvalidBlockRefs", "/api/search/listInvalidBlockRefs", JSONBody, ResponseOptions{}, "POST")
+
var UpdateEmbedBlock = define[UpdateEmbedBlockRequest, Null]("updateEmbedBlock", "/api/search/updateEmbedBlock", JSONBody, ResponseOptions{}, "POST")
+
var FullTextSearchAssetContent = define[SearchAssetContentRequest, SearchAssetContentData]("fullTextSearchAssetContent", "/api/search/fullTextSearchAssetContent", JSONBody, ResponseOptions{}, "POST")
+
var GetEmbedBlock = define[GetEmbedBlockRequest, EmbedBlocksData]("getEmbedBlock", "/api/search/getEmbedBlock", JSONBody, ResponseOptions{}, "POST")
+
var SearchEmbedBlock = define[SearchEmbedBlockRequest, EmbedBlocksData]("searchEmbedBlock", "/api/search/searchEmbedBlock", JSONBody, ResponseOptions{}, "POST")
+
var FindReplace = define[FindReplaceRequest, Null]("findReplace", "/api/search/findReplace", JSONBody, ResponseOptions{AdditionalCodes: []int{1}}, "POST")
+
var SemanticSearchBlock = define[SearchBlockRequest, SearchBlocksData]("semanticSearchBlock", "/api/search/semanticSearchBlock", JSONBody, ResponseOptions{}, "POST")
+
var FullTextSearchBlock = define[FullTextSearchBlockRequest, *FullTextSearchBlockData]("fullTextSearchBlock", "/api/search/fullTextSearchBlock", JSONBody, ResponseOptions{}, "POST")
+
var SearchRefBlock = define[SearchRefBlockRequest, SearchRefData]("searchRefBlock", "/api/search/searchRefBlock", JSONBody, ResponseOptions{DataOnError: true}, "POST")
var ListLoadedPlugins = define[EmptyRequest, []*LoadedPlugin]("listLoadedPlugins", "/api/plugin/listLoadedPlugins", NoBody, ResponseOptions{}, "POST")
@@ -676,6 +727,44 @@ var ResetRepo = define[EmptyRequest, Null]("resetRepo", "/api/repo/resetRepo", N
var PurgeRepo = define[EmptyRequest, Null]("purgeRepo", "/api/repo/purgeRepo", NoBody, ResponseOptions{}, "POST")
var PurgeCloudRepo = define[EmptyRequest, Null]("purgeCloudRepo", "/api/repo/purgeCloudRepo", NoBody, ResponseOptions{}, "POST")
+var MoveLocalShorthands = define[FileTreeNotebookRequest, []string]("moveLocalShorthands", "/api/filetree/moveLocalShorthands", JSONBody, ResponseOptions{}, "POST")
+var ListDocTree = define[FileTreePathRequest, FileTreeDocTreeData]("listDocTree", "/api/filetree/listDocTree", JSONBody, ResponseOptions{}, "POST")
+var UpsertIndexes = define[FileTreePathsRequest, Null]("upsertIndexes", "/api/filetree/upsertIndexes", JSONBody, ResponseOptions{}, "POST")
+var RemoveIndexes = define[FileTreePathsRequest, Null]("removeIndexes", "/api/filetree/removeIndexes", JSONBody, ResponseOptions{}, "POST")
+var Doc2Heading = define[FileTreeDocHeadingRequest, FileTreeDocHeadingData]("doc2Heading", "/api/filetree/doc2Heading", JSONBody, ResponseOptions{}, "POST")
+var Heading2Doc = define[FileTreeHeadingDocRequest, Null]("heading2Doc", "/api/filetree/heading2Doc", JSONBody, ResponseOptions{}, "POST")
+var Li2Doc = define[FileTreeListItemDocRequest, Null]("li2Doc", "/api/filetree/li2Doc", JSONBody, ResponseOptions{}, "POST")
+var GetHPathByPath = define[FileTreePathRequest, string]("getHPathByPath", "/api/filetree/getHPathByPath", JSONBody, ResponseOptions{}, "POST")
+var GetHPathsByPaths = define[FileTreePathsRequest, []string]("getHPathsByPaths", "/api/filetree/getHPathsByPaths", JSONBody, ResponseOptions{}, "POST")
+var GetHPathByID = define[FileTreeIDRequest, string]("getHPathByID", "/api/filetree/getHPathByID", JSONBody, ResponseOptions{}, "POST")
+var GetPathByID = define[FileTreeTrimIDRequest, FileTreeDocPathData]("getPathByID", "/api/filetree/getPathByID", JSONBody, ResponseOptions{}, "POST")
+var GetFullHPathByID = define[FileTreeOptionalIDRequest, *string]("getFullHPathByID", "/api/filetree/getFullHPathByID", JSONBody, ResponseOptions{}, "POST")
+var GetIDsByHPath = define[FileTreeOptionalPathRequest, []string]("getIDsByHPath", "/api/filetree/getIDsByHPath", JSONBody, ResponseOptions{}, "POST")
+var MoveDocs = define[FileTreeMoveRequest, Null]("moveDocs", "/api/filetree/moveDocs", JSONBody, ResponseOptions{}, "POST")
+var MoveDocsByID = define[FileTreeMoveIDsRequest, Null]("moveDocsByID", "/api/filetree/moveDocsByID", JSONBody, ResponseOptions{}, "POST")
+var RemoveDoc = define[FileTreePathRequest, Null]("removeDoc", "/api/filetree/removeDoc", JSONBody, ResponseOptions{}, "POST")
+var RemoveDocByID = define[FileTreeTrimIDRequest, Null]("removeDocByID", "/api/filetree/removeDocByID", JSONBody, ResponseOptions{}, "POST")
+var RemoveDocs = define[FileTreePathsRequest, Null]("removeDocs", "/api/filetree/removeDocs", JSONBody, ResponseOptions{}, "POST")
+var RenameDoc = define[FileTreeRenameRequest, Null]("renameDoc", "/api/filetree/renameDoc", JSONBody, ResponseOptions{}, "POST")
+var RenameDocByID = define[FileTreeRenameIDRequest, Null]("renameDocByID", "/api/filetree/renameDocByID", JSONBody, ResponseOptions{}, "POST")
+var DuplicateDoc = define[FileTreeIDRequest, FileTreeDuplicateData]("duplicateDoc", "/api/filetree/duplicateDoc", JSONBody, ResponseOptions{}, "POST")
+var CreateDoc = define[FileTreeCreateRequest, FileTreeCreateData]("createDoc", "/api/filetree/createDoc", JSONBody, ResponseOptions{}, "POST")
+var CreateDailyNote = define[FileTreeDailyNoteRequest, FileTreeCreateData]("createDailyNote", "/api/filetree/createDailyNote", JSONBody, ResponseOptions{AdditionalCodes: []int{1}}, "POST")
+var CreateDocWithMd = define[FileTreeCreateMarkdownRequest, string]("createDocWithMd", "/api/filetree/createDocWithMd", JSONBody, ResponseOptions{}, "POST")
+var GetDocCreateSavePath = define[FileTreeNotebookRequest, FileTreeCreateSavePathData]("getDocCreateSavePath", "/api/filetree/getDocCreateSavePath", JSONBody, ResponseOptions{}, "POST")
+var GetRefCreateSavePath = define[FileTreeNotebookRequest, FileTreeSavePathData]("getRefCreateSavePath", "/api/filetree/getRefCreateSavePath", JSONBody, ResponseOptions{}, "POST")
+var GetShorthandSavePath = define[FileTreeNotebookRequest, FileTreeSavePathData]("getShorthandSavePath", "/api/filetree/getShorthandSavePath", JSONBody, ResponseOptions{}, "POST")
+var ChangeSort = define[FileTreeChangeSortRequest, Null]("changeSort", "/api/filetree/changeSort", JSONBody, ResponseOptions{}, "POST")
+var ReorderDocs = define[FileTreeReorderRequest, *FileTreeReorderData]("reorderDocs", "/api/filetree/reorderDocs", StructJSONBody, ResponseOptions{DataOnError: true}, "POST")
+var SetSort = define[FileTreeSetSortRequest, *FileTreeSetSortData]("setSort", "/api/filetree/setSort", StructJSONBody, ResponseOptions{DataOnError: true}, "POST")
+var SetDocSortMode = define[FileTreeSortModeRequest, *FileTreeSortModeData]("setDocSortMode", "/api/filetree/setDocSortMode", StructJSONBody, ResponseOptions{DataOnError: true}, "POST")
+var SearchDocs = define[FileTreeSearchRequest, []*FileTreeSearchDoc]("searchDocs", "/api/filetree/searchDocs", JSONBody, ResponseOptions{}, "POST")
+var ListDocsByPath = define[FileTreeListRequest, FileTreeListData]("listDocsByPath", "/api/filetree/listDocsByPath", JSONBody, ResponseOptions{}, "POST")
+var GetDoc = define[FileTreeGetDocRequest, FileTreeGetDocData]("getDoc", "/api/filetree/getDoc", JSONBody, ResponseOptions{AdditionalCodes: []int{1, 3}}, "POST")
+var SetPublishAccess = define[FileTreeSetPublishRequest, Null]("setPublishAccess", "/api/filetree/setPublishAccess", JSONBody, ResponseOptions{}, "POST")
+var GetPublishAccess = define[FileTreePublishIDsRequest, FileTreePublishData]("getPublishAccess", "/api/filetree/getPublishAccess", JSONBody, ResponseOptions{}, "POST")
+var AuthFilePublishAccess = define[FileTreeAuthPublishRequest, Null]("authFilePublishAccess", "/api/filetree/authFilePublishAccess", JSONBody, ResponseOptions{AdditionalErrorStatuses: []int{429}}, "POST")
+
var ExportCodeBlock = define[ExportIDRequest, ExportPathData]("exportCodeBlock", "/api/export/exportCodeBlock", JSONBody, ResponseOptions{AdditionalCodes: []int{1}}, "POST")
var ExportAttributeView = define[ExportAttributeViewRequest, ExportZipData]("exportAttributeView", "/api/export/exportAttributeView", JSONBody, ResponseOptions{AdditionalCodes: []int{1}}, "POST")
var Export2Liandi = define[ExportIDRequest, Null]("export2Liandi", "/api/export/export2Liandi", JSONBody, ResponseOptions{}, "POST")
@@ -720,7 +809,7 @@ var RenameAsset = define[RenameAssetRequest, AssetRenameData]("renameAsset", "/a
var GetDocImageAssets = define[AssetDocumentRequest, []string]("getDocImageAssets", "/api/asset/getDocImageAssets", JSONBody, ResponseOptions{}, "POST")
var GetDocAssets = define[AssetDocumentAssetsRequest, []string]("getDocAssets", "/api/asset/getDocAssets", JSONBody, ResponseOptions{}, "POST")
var SetFileAnnotation = define[SetAssetAnnotationRequest, Null]("setFileAnnotation", "/api/asset/setFileAnnotation", JSONBody, ResponseOptions{}, "POST")
-var GetFileAnnotation = define[AssetPathRequest, AssetAnnotationData]("getFileAnnotation", "/api/asset/getFileAnnotation", JSONBody, ResponseOptions{AdditionalCodes: []int{1,403}}, "POST")
+var GetFileAnnotation = define[AssetPathRequest, AssetAnnotationData]("getFileAnnotation", "/api/asset/getFileAnnotation", JSONBody, ResponseOptions{AdditionalCodes: []int{1, 403}}, "POST")
var RemoveUnusedAsset = define[AssetPathRequest, AssetPathData]("removeUnusedAsset", "/api/asset/removeUnusedAsset", JSONBody, ResponseOptions{}, "POST")
var RemoveUnusedAssets = define[EmptyRequest, AssetPathsData]("removeUnusedAssets", "/api/asset/removeUnusedAssets", NoBody, ResponseOptions{}, "POST")
var GetUnusedAssets = define[EmptyRequest, []*AssetUnusedItem]("getUnusedAssets", "/api/asset/getUnusedAssets", NoBody, ResponseOptions{}, "POST")
@@ -731,41 +820,3 @@ var AssetUploadCloudByAssetsPaths = define[AssetPathsCloudUploadRequest, Null]("
var InsertLocalAssets = define[InsertLocalAssetsRequest, AssetUploadData]("insertLocalAssets", "/api/asset/insertLocalAssets", JSONBody, ResponseOptions{DataOnError: true}, "POST")
var InsertCover = define[InsertCoverRequest, AssetInsertCoverData]("insertCover", "/api/asset/insertCover", JSONBody, ResponseOptions{}, "POST")
var UploadAsset = define[UploadAssetRequest, AssetUploadData]("uploadAsset", "/api/asset/upload", MultipartBody, ResponseOptions{}, "POST")
-
-var MoveLocalShorthands = define[FileTreeNotebookRequest, []string]("moveLocalShorthands", "/api/filetree/moveLocalShorthands", JSONBody, ResponseOptions{}, "POST")
-var ListDocTree = define[FileTreePathRequest, FileTreeDocTreeData]("listDocTree", "/api/filetree/listDocTree", JSONBody, ResponseOptions{}, "POST")
-var UpsertIndexes = define[FileTreePathsRequest, Null]("upsertIndexes", "/api/filetree/upsertIndexes", JSONBody, ResponseOptions{}, "POST")
-var RemoveIndexes = define[FileTreePathsRequest, Null]("removeIndexes", "/api/filetree/removeIndexes", JSONBody, ResponseOptions{}, "POST")
-var Doc2Heading = define[FileTreeDocHeadingRequest, FileTreeDocHeadingData]("doc2Heading", "/api/filetree/doc2Heading", JSONBody, ResponseOptions{}, "POST")
-var Heading2Doc = define[FileTreeHeadingDocRequest, Null]("heading2Doc", "/api/filetree/heading2Doc", JSONBody, ResponseOptions{}, "POST")
-var Li2Doc = define[FileTreeListItemDocRequest, Null]("li2Doc", "/api/filetree/li2Doc", JSONBody, ResponseOptions{}, "POST")
-var GetHPathByPath = define[FileTreePathRequest, string]("getHPathByPath", "/api/filetree/getHPathByPath", JSONBody, ResponseOptions{}, "POST")
-var GetHPathsByPaths = define[FileTreePathsRequest, []string]("getHPathsByPaths", "/api/filetree/getHPathsByPaths", JSONBody, ResponseOptions{}, "POST")
-var GetHPathByID = define[FileTreeIDRequest, string]("getHPathByID", "/api/filetree/getHPathByID", JSONBody, ResponseOptions{}, "POST")
-var GetPathByID = define[FileTreeTrimIDRequest, FileTreeDocPathData]("getPathByID", "/api/filetree/getPathByID", JSONBody, ResponseOptions{}, "POST")
-var GetFullHPathByID = define[FileTreeOptionalIDRequest, *string]("getFullHPathByID", "/api/filetree/getFullHPathByID", JSONBody, ResponseOptions{}, "POST")
-var GetIDsByHPath = define[FileTreeOptionalPathRequest, []string]("getIDsByHPath", "/api/filetree/getIDsByHPath", JSONBody, ResponseOptions{}, "POST")
-var MoveDocs = define[FileTreeMoveRequest, Null]("moveDocs", "/api/filetree/moveDocs", JSONBody, ResponseOptions{}, "POST")
-var MoveDocsByID = define[FileTreeMoveIDsRequest, Null]("moveDocsByID", "/api/filetree/moveDocsByID", JSONBody, ResponseOptions{}, "POST")
-var RemoveDoc = define[FileTreePathRequest, Null]("removeDoc", "/api/filetree/removeDoc", JSONBody, ResponseOptions{}, "POST")
-var RemoveDocByID = define[FileTreeTrimIDRequest, Null]("removeDocByID", "/api/filetree/removeDocByID", JSONBody, ResponseOptions{}, "POST")
-var RemoveDocs = define[FileTreePathsRequest, Null]("removeDocs", "/api/filetree/removeDocs", JSONBody, ResponseOptions{}, "POST")
-var RenameDoc = define[FileTreeRenameRequest, Null]("renameDoc", "/api/filetree/renameDoc", JSONBody, ResponseOptions{}, "POST")
-var RenameDocByID = define[FileTreeRenameIDRequest, Null]("renameDocByID", "/api/filetree/renameDocByID", JSONBody, ResponseOptions{}, "POST")
-var DuplicateDoc = define[FileTreeIDRequest, FileTreeDuplicateData]("duplicateDoc", "/api/filetree/duplicateDoc", JSONBody, ResponseOptions{}, "POST")
-var CreateDoc = define[FileTreeCreateRequest, FileTreeCreateData]("createDoc", "/api/filetree/createDoc", JSONBody, ResponseOptions{}, "POST")
-var CreateDailyNote = define[FileTreeDailyNoteRequest, FileTreeCreateData]("createDailyNote", "/api/filetree/createDailyNote", JSONBody, ResponseOptions{AdditionalCodes: []int{1}}, "POST")
-var CreateDocWithMd = define[FileTreeCreateMarkdownRequest, string]("createDocWithMd", "/api/filetree/createDocWithMd", JSONBody, ResponseOptions{}, "POST")
-var GetDocCreateSavePath = define[FileTreeNotebookRequest, FileTreeCreateSavePathData]("getDocCreateSavePath", "/api/filetree/getDocCreateSavePath", JSONBody, ResponseOptions{}, "POST")
-var GetRefCreateSavePath = define[FileTreeNotebookRequest, FileTreeSavePathData]("getRefCreateSavePath", "/api/filetree/getRefCreateSavePath", JSONBody, ResponseOptions{}, "POST")
-var GetShorthandSavePath = define[FileTreeNotebookRequest, FileTreeSavePathData]("getShorthandSavePath", "/api/filetree/getShorthandSavePath", JSONBody, ResponseOptions{}, "POST")
-var ChangeSort = define[FileTreeChangeSortRequest, Null]("changeSort", "/api/filetree/changeSort", JSONBody, ResponseOptions{}, "POST")
-var ReorderDocs = define[FileTreeReorderRequest, *FileTreeReorderData]("reorderDocs", "/api/filetree/reorderDocs", StructJSONBody, ResponseOptions{DataOnError: true}, "POST")
-var SetSort = define[FileTreeSetSortRequest, *FileTreeSetSortData]("setSort", "/api/filetree/setSort", StructJSONBody, ResponseOptions{DataOnError: true}, "POST")
-var SetDocSortMode = define[FileTreeSortModeRequest, *FileTreeSortModeData]("setDocSortMode", "/api/filetree/setDocSortMode", StructJSONBody, ResponseOptions{DataOnError: true}, "POST")
-var SearchDocs = define[FileTreeSearchRequest, []*FileTreeSearchDoc]("searchDocs", "/api/filetree/searchDocs", JSONBody, ResponseOptions{}, "POST")
-var ListDocsByPath = define[FileTreeListRequest, FileTreeListData]("listDocsByPath", "/api/filetree/listDocsByPath", JSONBody, ResponseOptions{}, "POST")
-var GetDoc = define[FileTreeGetDocRequest, FileTreeGetDocData]("getDoc", "/api/filetree/getDoc", JSONBody, ResponseOptions{AdditionalCodes: []int{1, 3}}, "POST")
-var SetPublishAccess = define[FileTreeSetPublishRequest, Null]("setPublishAccess", "/api/filetree/setPublishAccess", JSONBody, ResponseOptions{}, "POST")
-var GetPublishAccess = define[FileTreePublishIDsRequest, FileTreePublishData]("getPublishAccess", "/api/filetree/getPublishAccess", JSONBody, ResponseOptions{}, "POST")
-var AuthFilePublishAccess = define[FileTreeAuthPublishRequest, Null]("authFilePublishAccess", "/api/filetree/authFilePublishAccess", JSONBody, ResponseOptions{AdditionalErrorStatuses: []int{429}}, "POST")
diff --git a/kernel/apicontract/http_content.go b/kernel/apicontract/http_content.go
new file mode 100644
index 0000000000..fcafafbfed
--- /dev/null
+++ b/kernel/apicontract/http_content.go
@@ -0,0 +1,55 @@
+package apicontract
+
+import (
+ "fmt"
+ "mime"
+ "strings"
+)
+
+// HTTPContentVariant 声明原始响应的状态和媒体类型组合。
+type HTTPContentVariant struct {
+ Status int `json:"status"`
+ ContentType string `json:"contentType"`
+}
+
+// HTTPContentOptions 用于具有固定响应格式的页面或文件入口,保留统一 JSON 错误信封。
+func HTTPContentOptions(variants ...HTTPContentVariant) ResponseOptions {
+ if len(variants) == 0 {
+ panic("HTTP content requires explicit response variants")
+ }
+ return ResponseOptions{Output: BinaryOutput, ErrorStatus: 200, ContentVariants: variants}
+}
+
+func SuccessHTTPContent(status int, contentType string, data []byte) Response[BinaryContent] {
+ return Response[BinaryContent]{binary: &BinaryContent{Status: status, ContentType: contentType, Bytes: data}}
+}
+
+func validateContentVariants(definition Definition) error {
+ if len(definition.ContentVariants) == 0 {
+ return nil
+ }
+ if definition.Output != BinaryOutput {
+ return fmt.Errorf("content variants require binary output: %s", definition.Name)
+ }
+ seen := map[HTTPContentVariant]bool{}
+ for _, variant := range definition.ContentVariants {
+ media, parameters, err := mime.ParseMediaType(variant.ContentType)
+ if err != nil || !strings.Contains(media, "/") || media != variant.ContentType || len(parameters) != 0 || variant.Status < 200 || variant.Status > 599 || variant.Status == 204 || variant.Status == 304 {
+ return fmt.Errorf("invalid HTTP content variant: %s", definition.Name)
+ }
+ if seen[variant] {
+ return fmt.Errorf("duplicate HTTP content variant: %s", definition.Name)
+ }
+ seen[variant] = true
+ }
+ return nil
+}
+
+func matchesContentVariant(variants []HTTPContentVariant, status int, media string) bool {
+ for _, variant := range variants {
+ if variant.Status == status && variant.ContentType == media {
+ return true
+ }
+ }
+ return false
+}
diff --git a/kernel/apicontract/http_content_test.go b/kernel/apicontract/http_content_test.go
new file mode 100644
index 0000000000..9e04f0710c
--- /dev/null
+++ b/kernel/apicontract/http_content_test.go
@@ -0,0 +1,70 @@
+package apicontract
+
+import (
+ "encoding/json"
+ "testing"
+)
+
+func TestHTTPContentVariants(t *testing.T) {
+ previous := definitions
+ t.Cleanup(func() { definitions = previous })
+ endpoint := define[EmptyRequest, BinaryContent]("page", "/test/page", NoBody, HTTPContentOptions(
+ HTTPContentVariant{200, "text/html"}, HTTPContentVariant{400, "text/html"}, HTTPContentVariant{403, "text/plain"}), "GET")
+ bundle, err := BuildBundle()
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, test := range []struct {
+ status int
+ media string
+ payload string
+ valid bool
+ }{
+ {200, "text/html; charset=utf-8", "<p>ok</p>", true},
+ {400, "text/html", "<p>invalid</p>", true},
+ {403, "text/plain; charset=utf-8", "forbidden", true},
+ {400, "text/plain", "invalid", false},
+ {201, "text/html", "<p>ok</p>", false},
+ {200, "image/png", "content", false},
+ {200, "application/json", `{"code":-1,"msg":"denied","data":null}`, true},
+ {200, "application/json", `{"code":0,"msg":"","data":null}`, false},
+ } {
+ err := bundle.ValidateHTTPResponse("GET", "/test/page", test.status, test.media, []byte(test.payload))
+ if (err == nil) != test.valid {
+ t.Fatalf("%d %s: %v", test.status, test.media, err)
+ }
+ }
+ response := SuccessHTTPContent(400, "text/html; charset=utf-8", []byte("<p>invalid</p>"))
+ if endpoint.Status(response) != 400 || string(response.Binary().Bytes) != "<p>invalid</p>" {
+ t.Fatal("raw response changed")
+ }
+ if _, err := json.Marshal(response); err == nil {
+ t.Fatal("raw response encoded as JSON")
+ }
+ t.Run("undeclared status", func(t *testing.T) {
+ defer func() {
+ if recover() == nil {
+ t.Fatal("undeclared status accepted")
+ }
+ }()
+ endpoint.Status(SuccessHTTPContent(500, "text/html", nil))
+ })
+}
+
+func TestHTTPContentDeclarations(t *testing.T) {
+ previous := definitions
+ t.Cleanup(func() { definitions = previous })
+ for _, variants := range [][]HTTPContentVariant{
+ {{200, "text/html"}, {200, "text/html"}},
+ {{204, "text/html"}},
+ {{101, "text/html"}},
+ {{200, "text/html; charset=utf-8"}},
+ {{200, "invalid"}},
+ } {
+ definitions = previous
+ define[EmptyRequest, BinaryContent]("invalidPage", "/test/page", NoBody, HTTPContentOptions(variants...), "GET")
+ if _, err := BuildBundle(); err == nil {
+ t.Fatalf("invalid variants accepted: %+v", variants)
+ }
+ }
+}
diff --git a/kernel/apicontract/response.go b/kernel/apicontract/response.go
index 63b2b1916a..fbf6dd01f2 100644
--- a/kernel/apicontract/response.go
+++ b/kernel/apicontract/response.go
@@ -3,12 +3,14 @@ package apicontract
import (
"encoding/json"
"fmt"
+ "mime"
"net/http"
"slices"
)
// BinaryContent 保留文件的原始字节和媒体类型,不经过 JSON 编码。
type BinaryContent struct {
+ Status int
ContentType string
Bytes []byte
}
@@ -32,7 +34,7 @@ func SuccessNoContent[Data any]() Response[Data] {
// Status 只为显式声明的非 JSON 协议使用独立错误状态。
func (e Endpoint[Request, Data]) Status(r Response[Data]) int {
if r.httpStatus != 0 {
- if e.definition.Output != "" || r.code == 0 || !slices.Contains(e.definition.AdditionalErrorStatuses, r.httpStatus) {
+ if (e.definition.Output != "" && e.definition.Output != SSEOutput) || r.code == 0 || !slices.Contains(e.definition.AdditionalErrorStatuses, r.httpStatus) {
panic("endpoint does not declare this JSON error status")
}
return r.httpStatus
@@ -49,6 +51,15 @@ func (e Endpoint[Request, Data]) Status(r Response[Data]) int {
if e.definition.Output == WebSocketOutput && r.code == 0 {
panic("WebSocket response requires an upgrade or rejection")
}
+ if r.stream != nil {
+ if e.definition.Output != SSEOutput || e.definition.SSE == nil {
+ panic("endpoint does not declare SSE output")
+ }
+ return 200
+ }
+ if e.definition.Output == SSEOutput && r.code == 0 {
+ panic("SSE response requires StreamSSE")
+ }
if r.noContent {
if e.definition.Output != DirectJSONOutput || !e.definition.NoContent {
panic("endpoint does not declare an empty response")
@@ -63,7 +74,19 @@ func (e Endpoint[Request, Data]) Status(r Response[Data]) int {
}
if e.definition.Output == BinaryOutput {
if r.binary != nil {
- return 200
+ status := r.binary.Status
+ if status == 0 {
+ status = 200
+ }
+ if len(e.definition.ContentVariants) > 0 {
+ media, _, err := mime.ParseMediaType(r.binary.ContentType)
+ if err != nil || !matchesContentVariant(e.definition.ContentVariants, status, media) {
+ panic("endpoint does not declare this HTTP content variant")
+ }
+ } else if status != 200 {
+ panic("endpoint does not declare this HTTP content status")
+ }
+ return status
}
if r.code == 0 {
panic("binary response requires SuccessBinary")
@@ -108,10 +131,20 @@ type Response[Data any] struct {
directJSON bool
noContent bool
upgrade func(http.ResponseWriter, *http.Request)
+ stream func(http.ResponseWriter, *http.Request)
websocketFailure bool
httpStatus int
+ afterWrite func()
+}
+
+// WithAfterWrite 将通知保留到响应写入完成后执行。
+func WithAfterWrite[Data any](response Response[Data], after func()) Response[Data] {
+ response.afterWrite = after
+ return response
}
+func (r Response[Data]) AfterWrite() func() { return r.afterWrite }
+
// WithHTTPStatus 只为声明过的业务错误保留额外 HTTP 状态。
func (e Endpoint[Request, Data]) WithHTTPStatus(response Response[Data], status int) Response[Data] {
response.httpStatus = status
@@ -145,22 +178,30 @@ func FailureWithTimeout[Data any](code int, msg string, milliseconds int) Respon
}
func (r Response[Data]) MarshalJSON() ([]byte, error) {
+ return r.MarshalWith(json.Marshal)
+}
+
+// MarshalWith 使用指定编码器序列化相同的有类型载荷,供大体量 JSON 响应保留快速编码路径。
+func (r Response[Data]) MarshalWith(marshal func(any) ([]byte, error)) ([]byte, error) {
+ if r.stream != nil {
+ return nil, fmt.Errorf("SSE stream cannot be encoded as JSON")
+ }
if r.upgrade != nil {
return nil, fmt.Errorf("WebSocket upgrade cannot be encoded as JSON")
}
if r.websocketFailure {
- return json.Marshal(r.data)
+ return marshal(r.data)
}
if r.noContent {
return nil, fmt.Errorf("empty response cannot be encoded as JSON")
}
if r.directJSON {
- return json.Marshal(r.data)
+ return marshal(r.data)
}
if r.binary != nil {
return nil, fmt.Errorf("binary response cannot be encoded as JSON")
}
- return json.Marshal(struct {
+ return marshal(struct {
Code int `json:"code"`
Msg string `json:"msg"`
Data any `json:"data"`
diff --git a/kernel/apicontract/response_encoder_test.go b/kernel/apicontract/response_encoder_test.go
new file mode 100644
index 0000000000..c1cfabf5cf
--- /dev/null
+++ b/kernel/apicontract/response_encoder_test.go
@@ -0,0 +1,44 @@
+package apicontract
+
+import (
+ "encoding/json"
+ "reflect"
+ "testing"
+
+ goccyJSON "github.com/goccy/go-json"
+)
+
+func TestResponseAlternateJSONEncoder(t *testing.T) {
+ type data struct {
+ Text string `json:"text"`
+ Count int64 `json:"count"`
+ Entries []string `json:"entries"`
+ }
+ for _, response := range []Response[data]{
+ Success(data{Text: "<value>", Count: 9007199254740993}),
+ FailureWithTimeout[data](1, "message", 7000),
+ } {
+ standard, err := json.Marshal(response)
+ if err != nil {
+ t.Fatal(err)
+ }
+ called := false
+ fast, err := response.MarshalWith(func(value any) ([]byte, error) {
+ called = true
+ return goccyJSON.Marshal(value)
+ })
+ if err != nil || !called {
+ t.Fatalf("encoder not used: %v", err)
+ }
+ var left, right map[string]json.RawMessage
+ if err := json.Unmarshal(standard, &left); err != nil {
+ t.Fatal(err)
+ }
+ if err := json.Unmarshal(fast, &right); err != nil {
+ t.Fatal(err)
+ }
+ if !reflect.DeepEqual(left, right) {
+ t.Fatalf("JSON changed: %s / %s", standard, fast)
+ }
+ }
+}
diff --git a/kernel/apicontract/schema.go b/kernel/apicontract/schema.go
index 84007a612d..160480b8f0 100644
--- a/kernel/apicontract/schema.go
+++ b/kernel/apicontract/schema.go
@@ -27,17 +27,19 @@ type Schema struct {
}
type EndpointSchema struct {
- Method string `json:"method"`
- Path string `json:"path"`
- Handler string `json:"handler"`
- Body BodyMode `json:"body"`
- Request *Schema `json:"request"`
- Response *Schema `json:"response"`
- Output OutputMode `json:"output,omitempty"`
- ErrorStatus int `json:"errorStatus,omitempty"`
- NoContent bool `json:"noContent,omitempty"`
- WebSocket *WebSocketSchema `json:"websocket,omitempty"`
- AdditionalErrorStatuses []int `json:"additionalErrorStatuses,omitempty"`
+ Method string `json:"method"`
+ Path string `json:"path"`
+ Handler string `json:"handler"`
+ Body BodyMode `json:"body"`
+ Request *Schema `json:"request"`
+ Response *Schema `json:"response"`
+ Output OutputMode `json:"output,omitempty"`
+ ErrorStatus int `json:"errorStatus,omitempty"`
+ NoContent bool `json:"noContent,omitempty"`
+ WebSocket *WebSocketSchema `json:"websocket,omitempty"`
+ SSE *SSESchema `json:"sse,omitempty"`
+ ContentVariants []HTTPContentVariant `json:"contentVariants,omitempty"`
+ AdditionalErrorStatuses []int `json:"additionalErrorStatuses,omitempty"`
}
type WebSocketSchema struct {
@@ -493,18 +495,38 @@ func BuildBundle() (*Bundle, error) {
b := &schemaBuilder{definitions: map[string]*Schema{}, owners: map[string]reflect.Type{}}
bundle := &Bundle{Dialect: "https://json-schema.org/draft/2020-12/schema", Definitions: b.definitions}
for _, definition := range Definitions() {
+ if definition.FastJSON && definition.Output != "" {
+ return nil, fmt.Errorf("fast JSON requires envelope output: %s", definition.Name)
+ }
+ if err := validateContentVariants(definition); err != nil {
+ return nil, err
+ }
for _, status := range definition.AdditionalErrorStatuses {
- if definition.Output != "" || status < 400 || status > 599 {
+ if (definition.Output != "" && definition.Output != SSEOutput) || status < 400 || status > 599 {
return nil, fmt.Errorf("invalid JSON error status: %s", definition.Name)
}
}
- if definition.Output != "" && definition.Output != BinaryOutput && definition.Output != DirectJSONOutput && definition.Output != WebSocketOutput {
+ if definition.Output != "" && definition.Output != BinaryOutput && definition.Output != DirectJSONOutput && definition.Output != WebSocketOutput && definition.Output != SSEOutput {
return nil, fmt.Errorf("unsupported response output: %s", definition.Name)
}
if definition.NoContent && definition.Output != DirectJSONOutput {
return nil, fmt.Errorf("empty responses require direct JSON output: %s", definition.Name)
}
var websocket *WebSocketSchema
+ var sse *SSESchema
+ if (definition.Output == SSEOutput) != (definition.SSE != nil) {
+ return nil, fmt.Errorf("SSE output requires event declarations: %s", definition.Name)
+ }
+ if definition.SSE != nil {
+ if definition.DataOnError || definition.ErrorStatus != 0 || definition.DataNonNullable {
+ return nil, fmt.Errorf("invalid SSE response options: %s", definition.Name)
+ }
+ var err error
+ sse, err = b.sseSchema(definition.SSE)
+ if err != nil {
+ return nil, err
+ }
+ }
if (definition.Output == WebSocketOutput) != (definition.WebSocket != nil) {
return nil, fmt.Errorf("WebSocket output requires message declarations: %s", definition.Name)
}
@@ -574,6 +596,9 @@ func BuildBundle() (*Bundle, error) {
if definition.Output == DirectJSONOutput || definition.Output == WebSocketOutput {
success = data
}
+ if definition.Output == SSEOutput {
+ success = &Schema{Type: "string"}
+ }
var codes []any
for _, code := range definition.ErrorCodes {
codes = append(codes, code)
@@ -593,7 +618,7 @@ func BuildBundle() (*Bundle, error) {
for _, method := range definition.Methods {
bundle.Endpoints = append(bundle.Endpoints, EndpointSchema{Method: method, Path: definition.Path, Handler: definition.Name,
Body: definition.Body, Request: request, Response: response, Output: definition.Output, ErrorStatus: definition.ErrorStatus, NoContent: definition.NoContent, WebSocket: websocket,
- AdditionalErrorStatuses: definition.AdditionalErrorStatuses})
+ AdditionalErrorStatuses: definition.AdditionalErrorStatuses, SSE: sse, ContentVariants: definition.ContentVariants})
}
}
sort.Slice(bundle.Endpoints, func(i, j int) bool {
@@ -623,7 +648,7 @@ func (b *Bundle) ValidateResponse(method, path string, payload []byte) error {
}
for _, endpoint := range b.Endpoints {
if endpoint.Method == method && endpoint.Path == path {
- if endpoint.Output == BinaryOutput || endpoint.Output == WebSocketOutput {
+ if endpoint.Output == BinaryOutput || endpoint.Output == WebSocketOutput || endpoint.Output == SSEOutput {
return fmt.Errorf("binary endpoint requires HTTP response validation")
}
return b.validate(endpoint.Response, value, "$")
@@ -654,11 +679,19 @@ func (b *Bundle) ValidateHTTPResponse(method, path string, status int, contentTy
if err != nil {
return fmt.Errorf("invalid response content type: %w", err)
}
- if endpoint.Output == BinaryOutput && status == 200 {
+ if endpoint.Output == BinaryOutput {
+ if len(endpoint.ContentVariants) == 0 && status == 200 || matchesContentVariant(endpoint.ContentVariants, status, mediaType) {
+ return nil
+ }
+ }
+ if endpoint.SSE != nil && status == 200 && mediaType == "text/event-stream" {
return nil
}
expectedStatus := 200
response := endpoint.Response
+ if endpoint.SSE != nil {
+ response = endpoint.Response.AnyOf[1]
+ }
for _, extraStatus := range endpoint.AdditionalErrorStatuses {
if status == extraStatus {
expectedStatus = status
diff --git a/kernel/apicontract/sse.go b/kernel/apicontract/sse.go
new file mode 100644
index 0000000000..23ffe98d2f
--- /dev/null
+++ b/kernel/apicontract/sse.go
@@ -0,0 +1,83 @@
+package apicontract
+
+import (
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "reflect"
+ "strings"
+)
+
+const SSEOutput OutputMode = "sse"
+
+// SSEEventDefinition 将事件名称与对应的 JSON 载荷类型绑定。
+type SSEEventDefinition struct {
+ name string
+ payload reflect.Type
+}
+
+func SSEEvent[Payload any](name string) SSEEventDefinition {
+ if strings.ContainsAny(name, "\r\n") {
+ panic("SSE event name cannot contain a newline")
+ }
+ return SSEEventDefinition{name: name, payload: reflect.TypeFor[Payload]()}
+}
+
+type SSEDefinition struct{ Events []SSEEventDefinition }
+type SSESchema struct {
+ Events map[string]*Schema `json:"events"`
+}
+
+func SSEOptions(events ...SSEEventDefinition) ResponseOptions {
+ return ResponseOptions{Output: SSEOutput, SSE: &SSEDefinition{Events: events}}
+}
+
+// StreamSSE 保留流的完整生命周期,适配器在请求上下文内执行写入与清理。
+func StreamSSE[Data any](serve func(http.ResponseWriter, *http.Request)) Response[Data] {
+ if serve == nil {
+ panic("SSE output requires a stream handler")
+ }
+ return Response[Data]{stream: serve}
+}
+
+func (r Response[Data]) Stream() func(http.ResponseWriter, *http.Request) { return r.stream }
+
+func (b *schemaBuilder) sseSchema(definition *SSEDefinition) (*SSESchema, error) {
+ if definition == nil || len(definition.Events) == 0 {
+ return nil, fmt.Errorf("SSE output requires event declarations")
+ }
+ result := &SSESchema{Events: map[string]*Schema{}}
+ for _, event := range definition.Events {
+ if _, exists := result.Events[event.name]; exists {
+ return nil, fmt.Errorf("duplicate SSE event: %s", event.name)
+ }
+ payload, err := b.schema(event.payload, false)
+ if err != nil {
+ return nil, err
+ }
+ result.Events[event.name] = payload
+ }
+ return result, nil
+}
+
+// ValidateSSEEvent 独立校验流事件;流建立前的错误由 HTTP 响应契约校验。
+func (b *Bundle) ValidateSSEEvent(method, path, name string, payload []byte) error {
+ for _, endpoint := range b.Endpoints {
+ if endpoint.Method != method || endpoint.Path != path {
+ continue
+ }
+ if endpoint.SSE == nil {
+ return fmt.Errorf("endpoint does not declare SSE events")
+ }
+ schema, exists := endpoint.SSE.Events[name]
+ if !exists {
+ return fmt.Errorf("undeclared SSE event: %s", name)
+ }
+ var value any
+ if err := json.Unmarshal(payload, &value); err != nil {
+ return err
+ }
+ return b.validate(schema, value, "$")
+ }
+ return fmt.Errorf("unregistered API contract: %s %s", method, path)
+}
diff --git a/kernel/apicontract/sse_test.go b/kernel/apicontract/sse_test.go
new file mode 100644
index 0000000000..6808ce1a7b
--- /dev/null
+++ b/kernel/apicontract/sse_test.go
@@ -0,0 +1,90 @@
+package apicontract
+
+import (
+ "net/http"
+ "reflect"
+ "testing"
+)
+
+type sseTestToken struct {
+ Token string `json:"token"`
+}
+
+func TestSSEDeclaredEvents(t *testing.T) {
+ builder := &schemaBuilder{definitions: map[string]*Schema{}, owners: map[string]reflect.Type{}}
+ options := SSEOptions(SSEEvent[sseTestToken]("content"), SSEEvent[sseTestToken](""))
+ schema, err := builder.sseSchema(options.SSE)
+ if err != nil {
+ t.Fatal(err)
+ }
+ bundle := &Bundle{Definitions: builder.definitions, Endpoints: []EndpointSchema{{Method: "POST", Path: "/events", SSE: schema}}}
+ for _, name := range []string{"content", ""} {
+ if err = bundle.ValidateSSEEvent("POST", "/events", name, []byte(`{"token":"text"}`)); err != nil {
+ t.Fatal(err)
+ }
+ }
+ for _, body := range []string{`{}`, `{"token":1}`, `null`, `[]`} {
+ if err = bundle.ValidateSSEEvent("POST", "/events", "content", []byte(body)); err == nil {
+ t.Fatalf("invalid event accepted: %s", body)
+ }
+ }
+ if err = bundle.ValidateSSEEvent("POST", "/events", "other", []byte(`{"token":"text"}`)); err == nil {
+ t.Fatal("undeclared event accepted")
+ }
+ if _, err = builder.sseSchema(&SSEDefinition{Events: []SSEEventDefinition{SSEEvent[sseTestToken]("x"), SSEEvent[sseTestToken]("x")}}); err == nil {
+ t.Fatal("duplicate event accepted")
+ }
+ if _, err = builder.sseSchema(&SSEDefinition{}); err == nil {
+ t.Fatal("empty event set accepted")
+ }
+}
+
+func TestSSEStreamResponse(t *testing.T) {
+ endpoint := Endpoint[EmptyRequest, Null]{definition: Definition{Output: SSEOutput, SSE: SSEOptions(SSEEvent[sseTestToken]("content")).SSE, AdditionalErrorStatuses: []int{409}}}
+ stream := StreamSSE[Null](func(http.ResponseWriter, *http.Request) {})
+ if endpoint.Status(stream) != 200 || stream.Stream() == nil {
+ t.Fatal("missing stream lifecycle")
+ }
+ if _, err := stream.MarshalJSON(); err == nil {
+ t.Fatal("stream serialized as an envelope")
+ }
+ if endpoint.Status(endpoint.WithHTTPStatus(Failure[Null](-1, "busy"), 409)) != 409 {
+ t.Fatal("SSE admission status changed")
+ }
+ defer func() {
+ if recover() == nil {
+ t.Fatal("undeclared stream accepted")
+ }
+ }()
+ Endpoint[EmptyRequest, Null]{}.Status(stream)
+}
+
+func TestSSEHTTPResponseKinds(t *testing.T) {
+ previous := definitions
+ t.Cleanup(func() { definitions = previous })
+ options := SSEOptions(SSEEvent[sseTestToken]("content"))
+ options.AdditionalErrorStatuses = []int{409}
+ define[EmptyRequest, Null]("events", "/test/events", NoBody, options, "POST")
+ bundle, err := BuildBundle()
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, test := range []struct {
+ status int
+ media string
+ body string
+ valid bool
+ }{
+ {200, "text/event-stream; charset=utf-8", "event: content\ndata: {\"token\":\"text\"}\n\n", true},
+ {200, "text/event-stream-invalid", "", false},
+ {201, "text/event-stream", "", false},
+ {200, "application/json", `{"code":-1,"msg":"invalid","data":null}`, true},
+ {409, "application/json", `{"code":-1,"msg":"busy","data":null}`, true},
+ {400, "application/json", `{"code":-1,"msg":"invalid","data":null}`, false},
+ {200, "application/json", `{"code":0,"msg":"","data":null}`, false},
+ } {
+ if err := bundle.ValidateHTTPResponse("POST", "/test/events", test.status, test.media, []byte(test.body)); (err == nil) != test.valid {
+ t.Fatalf("%d %s: %v", test.status, test.media, err)
+ }
+ }
+}
diff --git a/kernel/apicontract/typescript.go b/kernel/apicontract/typescript.go
index da3dff7833..10289f1c72 100644
--- a/kernel/apicontract/typescript.go
+++ b/kernel/apicontract/typescript.go
@@ -87,13 +87,18 @@ func (b *Bundle) typeScript(schema *Schema) string {
}
return "Array<" + b.typeScript(schema.Items) + ">"
case "object":
+ var indexSignature string
if additional, ok := schema.AdditionalProperties.(*Schema); ok {
if additional.Ref == "#/$defs/JSONValue" {
- return "{ [key: string]: JSONValue }"
+ indexSignature = "{ [key: string]: JSONValue }"
+ } else {
+ indexSignature = "Record<string, " + b.typeScript(additional) + ">"
}
- return "Record<string, " + b.typeScript(additional) + ">"
}
if len(schema.Properties) == 0 {
+ if indexSignature != "" {
+ return indexSignature
+ }
return "Record<string, never>"
}
required := map[string]bool{}
@@ -108,7 +113,11 @@ func (b *Bundle) typeScript(schema *Schema) string {
}
fields = append(fields, quote(key)+optional+": "+b.typeScript(schema.Properties[key])+";")
}
- return "{ " + strings.Join(fields, " ") + " }"
+ object := "{ " + strings.Join(fields, " ") + " }"
+ if indexSignature != "" {
+ return "(" + object + " & " + indexSignature + ")"
+ }
+ return object
default:
panic("unsupported TypeScript schema: " + schema.Type)
}
@@ -156,9 +165,20 @@ func (b *Bundle) TypeScript(legacy []Route) []byte {
statuses, _ := json.Marshal(endpoint.AdditionalErrorStatuses)
fmt.Fprintf(&output, " additionalErrorStatuses: %s;\n", statuses)
}
+ if len(endpoint.ContentVariants) > 0 {
+ variants, _ := json.Marshal(endpoint.ContentVariants)
+ fmt.Fprintf(&output, " contentVariants: %s;\n", variants)
+ }
if ws := endpoint.WebSocket; ws != nil {
fmt.Fprintf(&output, " websocket: { incoming: %s; outgoing: %s; failureStatus: %d; };\n", b.typeScript(ws.Incoming), b.typeScript(ws.Outgoing), ws.FailureStatus)
}
+ if sse := endpoint.SSE; sse != nil {
+ output.WriteString(" sse: { events: { ")
+ for _, name := range sortedKeys(sse.Events) {
+ fmt.Fprintf(&output, "%s: %s; ", quote(name), b.typeScript(sse.Events[name]))
+ }
+ output.WriteString("}; };\n")
+ }
output.WriteString(" };\n")
}
output.WriteString("}\n\n")
@@ -207,7 +227,7 @@ export type APICallbackResponse<R> = R extends {code: infer C extends number}
type APIDirectCallbackResponse<R> = R extends {code: number} ? APICallbackResponse<R> : R;
type APIPostTail<C extends APIContract> = [
- cb?: (response: C extends {output: "binary"} ? JSONValue : C extends {output: "directJSON"} ? APIDirectCallbackResponse<C["response"]> | (C extends {noContent: true} ? "" : never) : APICallbackResponse<C["response"]>) => void,
+ cb?: (response: C extends {output: "binary"} ? JSONValue : C extends {output: "directJSON"} ? APIDirectCallbackResponse<C["response"]> | (C extends {noContent: true} ? "" : never) : C extends {output: "sse"} ? string | APICallbackResponse<C["response"]> : APICallbackResponse<C["response"]>) => void,
headers?: Record<string, string>,
failCallback?: (response: APIFetchFailure) => void,
signal?: AbortSignal,
diff --git a/kernel/apicontract/typescript_properties_test.go b/kernel/apicontract/typescript_properties_test.go
new file mode 100644
index 0000000000..a5d5cc4dff
--- /dev/null
+++ b/kernel/apicontract/typescript_properties_test.go
@@ -0,0 +1,25 @@
+package apicontract
+
+import "testing"
+
+func TestTypeScriptKeepsPropertiesWithJSONExtensions(t *testing.T) {
+ bundle := &Bundle{}
+ schema := &Schema{
+ Type: "object",
+ Properties: map[string]*Schema{
+ "code": {Type: "number"},
+ "msg": {Type: "string"},
+ "token": {Type: "string"},
+ },
+ Required: []string{"code", "msg"},
+ AdditionalProperties: &Schema{Ref: "#/$defs/JSONValue"},
+ }
+ want := `({ "code": number; "msg": string; "token"?: string; } & { [key: string]: JSONValue })`
+ if got := bundle.typeScript(schema); got != want {
+ t.Fatalf("fixed fields or extension values changed: %s", got)
+ }
+ schema.Properties = nil
+ if got := bundle.typeScript(schema); got != "{ [key: string]: JSONValue }" {
+ t.Fatalf("plain JSON map changed: %s", got)
+ }
+}