用 Redux 实现简易的文本 OT 演示。

解读

国内前端面试中,“Redux + OT” 常被用来考察候选人对「不可变状态管理」与「协同冲突解决」的综合理解。
题目要求“简易”,意味着无需实现完整的 Google Docs 级 OT 引擎,但必须用 Redux 的三大原则(单一 Store、纯函数 Reducer、不可变 State)把「本地操作生成操作记录 → 远程操作变换 → 最终文本一致」这一闭环跑通。
面试官重点看:

  1. 状态设计是否扁平、可序列化;
  2. Reducer 是否纯函数、无副作用;
  3. 是否用中间件(redux-thunk 或 redux-saga)处理异步远程操作;
  4. 是否用时间旅行调试验证一致性。

知识点

  1. OT 基础模型:操作(op)= {type: 'retain'|'insert'|'delete', length?: number, text?: string}。
  2. 操作变换函数:transform(opA, opB) → [opA′, opB′],保证并发操作交换后收敛到同一状态。
  3. Redux 状态切片:
    • editor:{revision: number, content: string}
    • pending:本地已发送但未确认的操作队列
    • buffer:收到远程操作但本地 revision 落后时的缓冲队列
  4. 中间件职责:
    • 发送本地 op 时,先推入 pending,收到服务器 ACK 后再移除;
    • 收到远程 op 时,若 revision 匹配直接 apply,否则缓冲并等待缺失版本。
  5. 不可变更新:每次 apply 必须返回新 content 字符串,禁止 mutate。

答案

// 1. 状态定义
interface State {
  revision: number;
  content: string;
  pending: Op[];
  buffer: RemoteOp[];
}

// 2. 操作类型
type Op = { type: 'insert'; pos: number; text: string } |
          { type: 'delete'; pos: number; length: number };

interface RemoteOp extends Op { revision: number; }

// 3. 纯函数 Reducer
function editorReducer(state: State = initState, action: AnyAction): State {
  switch (action.type) {
    case 'LOCAL_INSERT':
    case 'LOCAL_DELETE': {
      const op = action.payload as Op;
      const newContent = applyOp(state.content, op);          // 纯函数
      return {
        ...state,
        content: newContent,
        pending: [...state.pending, op]
      };
    }
    case 'REMOTE_OP': {
      const rop = action.payload as RemoteOp;
      if (rop.revision === state.revision + 1) {
        // 无冲突,直接应用
        const newContent = applyOp(state.content, rop);
        return { ...state, content: newContent, revision: rop.revision };
      }
      if (rop.revision > state.revision + 1) {
        // 版本超前,缓冲
        return { ...state, buffer: [...state.buffer, rop].sort((a,b)=>a.revision-b.revision) };
      }
      // 版本落后,丢弃(服务器已保证顺序)
      return state;
    }
    case 'ACK_PENDING': {
      // 服务器确认,移除队首
      const [, ...rest] = state.pending;
      return { ...state, pending: rest };
    }
    default: return state;
  }
}

// 4. 操作变换(简易实现:仅处理并发插入)
function transform(a: Op, b: Op): [Op, Op] {
  if (a.type === 'insert' && b.type === 'insert') {
    if (a.pos <= b.pos) {
      return [a, { ...b, pos: b.pos + a.text!.length }];
    } else {
      return [{ ...a, pos: a.pos + b.text!.length }, b];
    }
  }
  // 其余情况简化:直接返回原操作(面试可说明完整实现需覆盖全部组合)
  return [a, b];
}

// 5. 中间件:发送与接收
const otMiddleware: Middleware = store => next => action => {
  if (action.type === 'LOCAL_INSERT' || action.type === 'LOCAL_DELETE') {
    // 异步发送
    sendToServer(action.payload).then(() => {
      store.dispatch({ type: 'ACK_PENDING' });
    });
  }
  return next(action);
};

// 6. 初始化 Store
const store = configureStore({
  reducer: editorReducer,
  middleware: getDefaultMiddleware => getDefaultMiddleware().concat(otMiddleware),
  devTools: true   // 开启时间旅行
});

使用示例:

store.dispatch({type:'LOCAL_INSERT', payload:{type:'insert', pos:5, text:'K'}});
// 远程收到并发插入
store.dispatch({type:'REMOTE_OP', payload:{type:'insert', pos:3, text:'X', revision:2}});

拓展思考

  1. Undo/Redo:在 Redux 里再维护一个 history: string[],每次 apply 后 push 当前 content,撤销时直接回退到上一版本,保证同样不可变。
  2. 多人光标同步:把光标位置也建模成操作 {type: 'cursor', userId, pos},用同一套 transform 函数调整,面试可提“状态即消息”思想。
  3. 性能优化:content 很大时,纯字符串 apply 会 O(n);可引入分段 Rope 或ImmutableJS 的 List,Reducer 返回新引用但共享结构,契合 Redux 的浅比较优化。
  4. 服务端方案:国内大厂如钉钉、腾讯文档,后端用Go/Java 实现 OT Engine,前端只需保证“幂等 + 顺序”即可;面试可强调“前后端协议对齐”是落地关键。