设计一个基于spec的节点端口类型检查系统

解读

国内 Clojure 岗位集中在数据管道、规则引擎、低代码平台等对“数据形态”极度敏感的场景。面试官抛出“节点端口类型检查”本质想看三件事:

  1. 你是否把 spec 当成“运行时契约”而非静态注释;
  2. 能否在“图结构”里做高效校验,而不是暴力遍历;
  3. 是否熟悉 Clojure 的“数据即代码”哲学——用纯数据描述图,用宏或函数生成校验逻辑,而不是硬编码 if/else。

因此答题要体现:spec 声明、图遍历、错误收集、性能与可扩展性四点,缺一不可。

知识点

  1. clojure.spec.alpha:s/def、s/valid?、s/conform、s/explain-data、multi-spec、自定义生成器
  2. 图模型:邻接表 vs 邻接矩阵;端口作为边属性;输入/输出方向用 qualified-keyword 区分
  3. 校验策略:
    • 深度优先 + 记忆化,避免重复校验同一节点
    • 失败快速返回 vs 收集全部错误——面试时要主动问业务需求,国内倾向“一次给全错误”
  4. 错误定位:使用 clojure.spec 的 via 路径 + 自定义 :reason 字段,前端可直接高亮端口
  5. 与 Java 生态互操作:如果图编辑器是 JavaFX 或 SWT,需提供 Java API validateGraph(Object edn),用 gen-class 暴露
  6. 性能:对于 10w+ 节点的风控规则图,用 core.async 做并行校验,或把 spec 编译成字节码(spec-alpha2 的 st/instrument 编译模式)

答案

(ns port-check.core
  (:require [clojure.spec.alpha :as s]
            [clojure.walk :as walk]
            [clojure.set :as set]))

;;;;;;;;;;;;;;;;
;; 1. 数据模型
(s/def ::node-id keyword?)
(s/def ::port-id keyword?)
(s/def ::dir #{:in :out})
(s/def ::type #{:int :string :bool :double :map})

(s/def ::port (s/keys :req [::port-id ::dir ::type]))
(s/def ::ports (s/coll-of ::port :kind vector? :distinct true))

(s/def ::node (s/keys :req [::node-id ::ports]))
(s/def ::graph (s/map-of ::node-id ::node))

;;;;;;;;;;;;;;;;
;; 2. 边模型:用“三元素向量”表示边 [from-node from-port to-node to-port]
(s/def ::edge (s/tuple ::node-id ::port-id ::node-id ::port-id))
(s/def ::edges (s/coll-of ::edge :kind vector?))

;;;;;;;;;;;;;;;;
;; 3. 全局校验上下文
(def ^:dynamic *errors* (atom []))

(defn- port-key [node-id port-id dir]
  (keyword (str (name node-id) "." (name port-id) "." (name dir))))

(defn- collect-error!
  "把错误统一收集,方便一次性返回给前端"
  [path reason edge]
  (swap! *errors* conj {:path path :reason reason :edge edge}))

;;;;;;;;;;;;;;;;
;; 4. 核心校验逻辑
(defn- check-port!
  "校验一条边两端的端口类型是否兼容"
  [graph [from-nid from-pid to-nid to-pid]]
  (let [from-node (get graph from-nid)
        to-node   (get graph to-nid)
        from-port (first (filter #(= (::port-id %) from-pid) (::ports from-node)))
        to-port   (first (filter #(= (::port-id %) to-pid)   (::ports to-node)))]
    (cond
      (nil? from-port)
      (collect-error! [::from-port-missing]
                      (str "节点 " from-nid " 缺少输出端口 " from-pid)
                      [from-nid from-pid to-nid to-pid])

      (nil? to-port)
      (collect-error! [::to-port-missing]
                      (str "节点 " to-nid " 缺少输入端口 " to-pid)
                      [from-nid from-pid to-nid to-pid])

      (not= (::type from-port) (::type to-port))
      (collect-error! [::type-mismatch]
                      (str "类型不匹配:"
                           (name from-nid) "/" (name from-pid) " 输出 " (::type from-port)
                           " -> "
                           (name to-nid) "/" (name to-pid) " 输入 " (::type to-port))
                      [from-nid from-pid to-nid to-pid])

      :else true)))

(defn validate-graph
  "对外 API,返回 {:ok? true} 或 {:ok? false :errors [...]}"
  [graph edges]
  (binding [*errors* (atom [])]
    (doseq [e edges] (check-port! graph e))
    (let [errs @*errors*]
      (if (empty? errs)
        {:ok? true}
        {:ok? false :errors errs}))))

;;;;;;;;;;;;;;;;
;; 5. 使用示例
(comment
  (def g {::node-a {::node-id ::node-a
                     ::ports [{::port-id ::p1 ::dir :out ::type :int}
                              {::port-id ::p2 ::dir :in  ::type :string}]}
          ::node-b {::node-id ::node-b
                     ::ports [{::port-id ::p3 ::dir :in  ::type :int}]}})

  (def es [[::node-a ::p1 ::node-b ::p3]])

  (validate-graph g es)
  ;; => {:ok? true}

  (def es-bad [[::node-a ::p2 ::node-b ::p3]]) ; string -> int
  (validate-graph g es-bad)
  ;; => {:ok? false
  ;;     :errors [{:path [:port-check.core/type-mismatch]
  ;;               :reason "类型不匹配:node-a/p2 输出 string -> node-b/p3 输入 int"
  ;;               :edge [:node-a :p2 :node-b :p3]}]}
  )

该实现特点:

  • 用纯数据描述图与边,与前端 JSON/EDN 无缝打通;
  • 错误信息带“路径”与“原因”,方便可视化编辑器高亮;
  • 校验函数无副作用(errors 用动态绑定隔离),可并行化;
  • 所有关键字均用 :: 限定,避免与客户代码冲突,符合国内大型团队“多模块协作”规范。

拓展思考

  1. 循环类型推导:如果节点是“泛型”块(例如加法器 T->T->T),需要用 spec 的 fspec + multi-spec 实现“类型变量统一”,把图当成约束系统求解。
  2. 增量校验:在可视化拖拽场景,每次只改一条边。可用 clojure.data/diff 维护“脏边集合”,避免全图重校验;对 10w+ 节点可做到 <50ms 响应。
  3. 代码生成:把校验通过的图直接编译成 Java 字节码或 Flink 作业,利用 spec 的生成器在编译前自动生成单元测试,形成“类型正确 => 运行时正确”的闭环。
  4. 双向端口:国内低代码平台常出现“可输入也可输出”的端口。可把 dir 扩展为 #{:in :out :bidir},并在 check-port! 里增加对称校验逻辑。
  5. 与 Maven 私服集成:把节点类型定义打包成 spec 契约 jar,供上下游团队依赖;在 CI 阶段用 clojure.spec.test.alpha/check 做自动化契约测试,防止“接口悄悄变宽”。