1.关于OT
假如 A 用户看到一段初始文本,内容是 “abc”,然后 A 想 第 3 个位置后面,插入”d” => “abcd”
假如 B 用户看到一段初始文本,内容是 “abc”, 然后 B 想在第 3 个位置后面插入”e” => “abce”
不做锁处理或者丢处理,那我们就保留最大内容(A,B先后执行),应该是 “abcde”, 如何按实际执行结果来看:
如果各自操作,没有 OT算法的处理,那么 A 看到的内容就会是 “abced”(A在第 3 个位置后面,然后 B 想在第 3 个位置后面插入”e” => abce),对于 B 用户而言,他实际上得到了一个顺序执行,就是 B 想在第 3 个位置后面插入”e” => abce , 然后 A 想 第 3 个位置后面插入”d”,最后得到的就是 "abcde", B的结果刚好复合,这个时候B是对的,A就是错的,所以 A 最终看到的不应该是原始的B操作,而是转化后的,他应该得到 “B想在第4个位置后插入e”,因此,我们要引入一个OT算法,最终结果就是说:
文本内容 = A内容 x B’ = A内容 x follow(A,B) = merge(A,B) = B内容 x A’ = B x follow(B,A)
Follow函数 的第一个参数代表第一个执行的操作,第二个参数代表后执行的操作
Merge代表合并后的最大可用集合
2.关于服务器设计
服务器中维护了一系列历史的修改版本,例如r1,r2,r3,…r100,…r110
假如某个客户端提交的变化C,是基于R100的,这时候,我们需要不停的产生变化 newC = follow(R101,C) , 然后 newC = follow(R102,newC),不断执行,最后要得到针对 r110这个版本的newC变化,推送到各个客户端
ot.js的核心实现
// Call this method whenever you receive an operation from a client.
Server.prototype.receiveOperation = function (revision, operation) {
if (revision < 0 || this.operations.length < revision) {
throw new Error("operation revision not in history");
}
// Find all operations that the client didn't know of when it sent the
// operation ...[0,1,2,3,4,5]// 1,operstion => [2,3,4,5]
var concurrentOperations = this.operations.slice(revision);
// ... and transform the operation against all these operations ...
var transform = operation.constructor.transform;
for (var i = 0; i < concurrentOperations.length; i++) {
// operation , [2,3,4,5][index]
operation = transform(operation, concurrentOperations[i])[0];
}
// ... and apply that on the document.
this.document = operation.apply(this.document);
// Store operation in history.
this.operations.push(operation);
// It's the caller's responsibility to send the operation to all connected
// clients and an acknowledgement to the creator.
return operation;
};
3. OT算法可视化
http://operational-transformation.github.io/visualization.html
更多参考:
https://www3.ntu.edu.sg/home/czsun/projects/otfaq/
http://operational-transformation.github.io/ot-for-javascript.html
http://operational-transformation.github.io/visualization.html