delta.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  1. import {Buffer} from "buffer";
  2. import {PrimitiveValue, UUID} from "./types";
  3. import { buffersXOR } from "./util/buffer_xor";
  4. type ConflictType = "U/U" | "R/U" | "R*/U" | "U/D" | "D/D";
  5. export abstract class Delta {
  6. readonly hash: Buffer;
  7. readonly description: string;
  8. readonly conflictsWith: [Delta, ConflictType][] = [];
  9. readonly partOf: Transaction[] = [];
  10. constructor(hash: Buffer, description: string) {
  11. this.hash = hash;
  12. this.description = description;
  13. }
  14. abstract getDependencies(): readonly [Delta,string][];
  15. hasTransitiveDependency(other: Delta) {
  16. if (this === other) return true;
  17. for (const [d] of this.getDependencies()) {
  18. if (d.hasTransitiveDependency(other)) return true;
  19. }
  20. return false;
  21. }
  22. serialize(): any {
  23. return {
  24. hash: this.hash.toString('hex'),
  25. type: this.constructor.name,
  26. }
  27. }
  28. abstract iterPrimitiveDeltas(): Generator<PrimitiveDelta>;
  29. }
  30. export abstract class PrimitiveDelta extends Delta {
  31. // constructor(hash: Buffer, description: string) {
  32. // super(has, description);
  33. // }
  34. *iterPrimitiveDeltas() {
  35. yield this;
  36. }
  37. }
  38. function registerConflict(d1: Delta, d2: Delta, type: ConflictType) {
  39. d1.conflictsWith.push([d2, type]);
  40. d2.conflictsWith.push([d1, type]);
  41. }
  42. export class NodeCreation extends PrimitiveDelta {
  43. readonly id: UUID;
  44. // Inverse dependencies
  45. readonly outgoingEdges: Map<string, NewEdge> = new Map();
  46. readonly incomingEdges: EdgeUpdate[] = []; // all deltas EVER that set this node as target of an edge.
  47. readonly readAllOutgoing: ReadAllOutgoing[] = [];
  48. readonly deletions: NodeDeletion[] = [];
  49. constructor(hash: Buffer, id: UUID) {
  50. super(hash, `NEW(${JSON.stringify(id)})`);
  51. this.id = id;
  52. }
  53. getDependencies(): [Delta,string][] {
  54. return [];
  55. }
  56. createOutgoingEdge(label: string, after: ReadAllOutgoing[] = []): NewEdge {
  57. const edgeId = label + ':' + buffersXOR(...after.map(a => a.hash)).toString('hex');
  58. return this.outgoingEdges.get(edgeId) || (() => {
  59. const newEdge = new NewEdge(this, label, after, edgeId);
  60. this.outgoingEdges.set(edgeId, newEdge);
  61. return newEdge;
  62. })();
  63. }
  64. registerOutgoingEdge(u: EdgeUpdate) {
  65. // A new outgoing edge will always conflict with all existing deletions.
  66. for (const d of this.deletions) {
  67. registerConflict(d, u, "U/D");
  68. }
  69. for (const r of this.readAllOutgoing) {
  70. if (!(u.overwrites as NewEdge).after.includes(r)) {
  71. registerConflict(r, u, "R*/U");
  72. }
  73. }
  74. // outgoing edge already stored in Edge.
  75. }
  76. registerIncomingEdge(u: EdgeUpdate) {
  77. // A new incoming edge always will conflict with all existing deletions.
  78. for (const d of this.deletions) {
  79. registerConflict(d, u, "U/D");
  80. }
  81. this.incomingEdges.push(u);
  82. }
  83. registerDeletion(d: NodeDeletion) {
  84. // A new deletion will conflict with all earliest incoming/outgoing edge operations that the deletion does not transitively explicitly depend on.
  85. for (const o of this.outgoingEdges.values()) {
  86. for (const u of o.iterOverwriters(u => !d.afterSrc.some(a => a.hasTransitiveDependency(u)))) {
  87. registerConflict(d, u, "U/D");
  88. }
  89. }
  90. for (const i of this.incomingEdges.filter(i => !d.afterTgt.some(a => a.hasTransitiveDependency(i)))) {
  91. registerConflict(i, d, "U/D");
  92. }
  93. // Delete/Delete conflict
  94. for (const other of this.deletions) {
  95. if (other !== d) {
  96. registerConflict(d, other, "D/D");
  97. }
  98. }
  99. this.deletions.push(d);
  100. }
  101. registerReadAllOutgoing(r: ReadAllOutgoing) {
  102. // ReadAllOutgoing will conflict with all outgoing edge creations that are not a dependency of ReadAllOutgoing
  103. // (in essence just a R/W conflict)
  104. for (const o of this.outgoingEdges.values()) {
  105. if (!r.after.includes(o)) {
  106. // TODO: We could turn NewEdge into an actual delta type. Then we could just conflict with that delta (possibly more efficient, maybe more elegant)
  107. for (const u of o.overwrittenBy) {
  108. registerConflict(r, u, "R*/U");
  109. }
  110. }
  111. }
  112. this.readAllOutgoing.push(r);
  113. }
  114. serialize(): any {
  115. return {...super.serialize(), id: this.id};
  116. }
  117. }
  118. // This delta represents getting all outgoing edges of a node.
  119. // For instance, when getting all the elements of a set (e.g., when checking some constraint), or iterating over a dictionary.
  120. export class ReadAllOutgoing extends PrimitiveDelta {
  121. // Dependencies:
  122. readonly node: NodeCreation;
  123. readonly after: readonly NewEdge[];
  124. constructor(hash: Buffer, node: NodeCreation, after: readonly NewEdge[]) {
  125. super(hash, `R*(${node.id})`);
  126. this.node = node;
  127. this.after = after;
  128. // Register inverse dependencies:
  129. node.registerReadAllOutgoing(this);
  130. }
  131. getDependencies(): [Delta, string][] {
  132. return [
  133. [this.node, "N"],
  134. ...([] as [Delta,string][]).concat(...this.after.map(a => a.overwrittenBy.map(u => [u, "A"] as [Delta, string]))),
  135. ];
  136. }
  137. }
  138. export class NodeDeletion extends PrimitiveDelta {
  139. // Dependencies:
  140. node: NodeCreation;
  141. afterSrc: readonly EdgeUpdate[];
  142. afterTgt: readonly EdgeUpdate[];
  143. constructor(hash: Buffer, node: NodeCreation, afterSrc: readonly EdgeUpdate[], afterTgt: readonly EdgeUpdate[]) {
  144. super(hash, `DEL(${JSON.stringify(node.id)})`);
  145. this.node = node;
  146. this.afterSrc = afterSrc;
  147. this.afterTgt = afterTgt;
  148. if (afterSrc.some(a => a.target.value !== null)) {
  149. throw new Error("NodeDeletion can only depend on EdgeUpdates that set outgoing edges to null.");
  150. }
  151. if (afterTgt.some(a => a.target.value === node)) {
  152. throw new Error("NodeDeletion cannot depend on EdgeUpdates that set incoming edges to node being deleted.");
  153. }
  154. // Register our dependencies' inverse dependencies + detect conflicts:
  155. node.registerDeletion(this);
  156. }
  157. getDependencies(): [Delta, string][] {
  158. return [
  159. [this.node, "D"],
  160. ...this.afterSrc.map(u => [u, "A"] as [Delta, string]),
  161. ...this.afterTgt.map(u => [u, "A"] as [Delta, string]),
  162. ];
  163. }
  164. serialize(): any {
  165. return {
  166. ...super.serialize(),
  167. node: this.node.hash.toString('hex'),
  168. afterSrc: this.afterSrc.map(u => u.hash.toString('hex')),
  169. afterTgt: this.afterTgt.map(u => u.hash.toString('hex')),
  170. };
  171. }
  172. }
  173. // Detects write/write and write/read conflicts.
  174. export abstract class Edge {
  175. readonly source: NodeCreation;
  176. readonly label: string;
  177. // Inverse dependencies
  178. readonly overwrittenBy: EdgeUpdate[] = [];
  179. readonly readBy: EdgeUpdate[] = [];
  180. constructor(source: NodeCreation, label: string) {
  181. this.source = source;
  182. this.label = label;
  183. }
  184. abstract getDependencies(): [Delta,string][];
  185. abstract serialize(): any;
  186. // Iterate over all overwriters, from early to late, depth-first.
  187. // When in some branch the 'condition' is satisfied, the satisfying element is yielded, and the descendants ignored.
  188. *iterOverwriters(filter: (u: EdgeUpdate) => boolean): Iterable<EdgeUpdate> {
  189. for (const ovr of this.overwrittenBy) {
  190. if (filter(ovr)) {
  191. yield ovr;
  192. }
  193. else {
  194. yield* ovr.overwritable.iterOverwriters(filter);
  195. }
  196. }
  197. }
  198. registerWrite(write: EdgeUpdate) {
  199. for (const other of this.overwrittenBy) {
  200. // A write conflicts with all other writes:
  201. registerConflict(write, other, "U/U");
  202. }
  203. for (const read of this.readBy) {
  204. if (read !== write && !write.afterReads.includes(read)) {
  205. // A write conflicts with all reads:
  206. registerConflict(read, write, "R/U");
  207. }
  208. }
  209. this.overwrittenBy.push(write);
  210. // Also check conflicts with deletions of source:
  211. this.source.registerOutgoingEdge(write);
  212. }
  213. registerRead(read: EdgeUpdate) {
  214. for (const write of this.overwrittenBy) {
  215. if (read !== write) {
  216. // A read conflicts with all writes:
  217. registerConflict(read, write, "R/U");
  218. }
  219. }
  220. this.readBy.push(read);
  221. }
  222. }
  223. // An Edge that does not yet have a target
  224. export class NewEdge extends Edge {
  225. readonly after: readonly ReadAllOutgoing[];
  226. readonly edgeId: string;
  227. constructor(source: NodeCreation, label: string, after: readonly ReadAllOutgoing[], edgeId: string) {
  228. super(source, label);
  229. this.after = after;
  230. this.edgeId = edgeId;
  231. }
  232. getDependencies(): [Delta,string][] {
  233. return [[this.source, "SRC"]];
  234. }
  235. serialize() {
  236. return {
  237. type: "NewEdge",
  238. source: this.source.hash.toString('hex'),
  239. label: this.label,
  240. };
  241. }
  242. }
  243. // An Edge that has been assigned a target (by an EdgeUpdate) at least once.
  244. export class ExistingEdge extends Edge {
  245. readonly delta: EdgeUpdate;
  246. constructor(source: NodeCreation, label: string, delta: EdgeUpdate) {
  247. super(source, label);
  248. this.delta = delta;
  249. }
  250. getDependencies(): [Delta,string][] {
  251. return [[this.delta, "U"]];
  252. }
  253. serialize() {
  254. return {
  255. type: "ExistingEdge",
  256. overwrites: this.delta.hash.toString('hex'),
  257. };
  258. }
  259. }
  260. // Target of an edge
  261. export interface Target {
  262. value: NodeCreation | PrimitiveValue;
  263. registerDependency(u: EdgeUpdate): void;
  264. getDependencies(): [Delta, string][];
  265. serialize(): any;
  266. }
  267. export class TargetNode implements Target {
  268. value: NodeCreation;
  269. constructor(value: NodeCreation) {
  270. this.value = value;
  271. }
  272. registerDependency(u: EdgeUpdate): void {
  273. this.value.registerIncomingEdge(u);
  274. }
  275. getDependencies(): [Delta, string][] {
  276. return [[this.value, "TGT"]];
  277. }
  278. serialize() {
  279. return {type: "TargetNode", node: this.value.hash.toString('hex')};
  280. }
  281. }
  282. export class TargetValue implements Target {
  283. value: PrimitiveValue;
  284. constructor(value: PrimitiveValue) {
  285. this.value = value;
  286. }
  287. registerDependency(): void {}
  288. getDependencies(): [Delta, string][] {
  289. return [];
  290. }
  291. serialize() {
  292. return {type: "TargetValue", value: this.value};
  293. }
  294. }
  295. export class EdgeUpdate extends PrimitiveDelta {
  296. // Dependencies
  297. readonly overwrites: Edge;
  298. readonly reads: readonly ExistingEdge[];
  299. readonly target: Target;
  300. readonly afterReads: readonly EdgeUpdate[];
  301. // Inverse dependencies
  302. readonly overwritable: ExistingEdge;
  303. constructor(hash: Buffer, overwrites: Edge, target: Target, reads: readonly ExistingEdge[], afterReads: readonly EdgeUpdate[]) {
  304. super(hash, `U(${overwrites.label}->${target.value instanceof NodeCreation ? target.value.description : target.value})`);
  305. // Record our own dependencies:
  306. this.overwrites = overwrites;
  307. this.target = target;
  308. this.reads = reads;
  309. this.afterReads = afterReads;
  310. this.overwritable = new ExistingEdge(overwrites.source, overwrites.label, this);
  311. // Register our dependencies' inverse dependencies + detect conflicts:
  312. overwrites.registerWrite(this);
  313. reads.forEach(r => r.registerRead(this));
  314. target.registerDependency(this);
  315. }
  316. // Makes code slightly easier to read
  317. overwrite() {
  318. return this.overwritable;
  319. }
  320. // Makes code slightly easier to read
  321. read() {
  322. return this.overwritable;
  323. }
  324. getDependencies(): [Delta,string][] {
  325. return this.overwrites.getDependencies()
  326. .concat(this.target.getDependencies())
  327. .concat(this.reads.map(r => [r.delta, "R"] as [Delta,string]))
  328. .concat(this.afterReads.map(a => [a, "A"] as [Delta, string]));
  329. }
  330. serialize(): any {
  331. return {
  332. ...super.serialize(),
  333. overwrites: this.overwrites.serialize(),
  334. target: this.target.serialize(),
  335. reads: this.reads.map(r => r.serialize()),
  336. afterReads: this.afterReads.map(a => a.hash.toString('hex')),
  337. };
  338. }
  339. }
  340. // export class EdgeRead extends PrimitiveDelta {
  341. // // Every read has a unique ID (otherwise, different concurrent reads would be represented by the same delta)
  342. // readonly id: UUID;
  343. // // Dependencies
  344. // readonly reads: ExistingEdge;
  345. // constructor(hash: Buffer, id: UUID, reads: ExistingEdge) {
  346. // super(hash, `R(${reads.label})`);
  347. // // Record our own dependencies:
  348. // this.reads = reads;
  349. // reads.registerRead(this);
  350. // }
  351. // serialize(): any {
  352. // return {
  353. // ...super.serialize(),
  354. // id: this.id,
  355. // reads: this.reads.map(r => r.serialize()),
  356. // };
  357. // }
  358. // }
  359. export class Transaction extends Delta {
  360. readonly deltas: readonly Delta[];
  361. readonly dependencies: readonly [Transaction, string][];
  362. constructor(hash: Buffer, deltas: readonly Delta[], description: string, dependencies: readonly [Transaction, string][]) {
  363. super(hash, description);
  364. this.deltas = deltas;
  365. this.dependencies = dependencies;
  366. // TODO: validate dependencies.
  367. // Derive conflicts from deltas
  368. for (const delta of deltas) {
  369. for (const [conflictingDelta, conflictType] of delta.conflictsWith) {
  370. if (deltas.includes(conflictingDelta)) {
  371. throw new Error("Cannot create a composite delta out of conflicting deltas");
  372. }
  373. const conflictingTxs = conflictingDelta.partOf;
  374. for (const otherTx of conflictingTxs) {
  375. if (!this.conflictsWith.some(([c]) => c === otherTx)) {
  376. registerConflict(this, otherTx, conflictType);
  377. }
  378. }
  379. }
  380. }
  381. for (const [dependency] of dependencies) {
  382. for (const [c, conflictKind] of this.conflictsWith) {
  383. if (c === dependency) {
  384. // // only for debugging, print all the detailed dependencies:
  385. // const detailedDependencies: [Delta,Delta,string][] = [];
  386. // for (const d of deltas) {
  387. // for (const d2 of dependency.deltas) {
  388. // for (const [dd, kind] of d.getDependencies()) {
  389. // if (dd === d2) {
  390. // detailedDependencies.push([d, d2, kind]);
  391. // }
  392. // }
  393. // }
  394. // }
  395. // console.log({tx: deltas, dependency: dependency.deltas, detailedDependencies});
  396. throw new Error(`Assertion failed: Transaction '${description}' (${hash.toString('hex').substring(0,8)}) depends on another conflicting (${conflictKind}) transaction '${dependency.description}' (${dependency.hash.toString('hex').substring(0,8)}).`);
  397. }
  398. }
  399. }
  400. deltas.forEach(d => d.partOf.push(this));
  401. }
  402. getDependencies(): readonly [Delta,string][] {
  403. return this.dependencies;
  404. }
  405. serialize(): any {
  406. return {
  407. ...super.serialize(),
  408. deltas: this.deltas.map(d => d.hash.toString('hex')),
  409. description: this.description,
  410. dependencies: this.dependencies.map(([d, kind]) => ({tx: d.hash.toString('hex'), kind})),
  411. };
  412. }
  413. *iterPrimitiveDeltas() {
  414. for (const d of this.deltas) {
  415. yield* d.iterPrimitiveDeltas();
  416. }
  417. }
  418. }
  419. // Given a set of deltas that we are trying to glue together in a (new) transaction, what other transactions should this new transaction depend on?
  420. // Argument 'currentDeltas' is a set of deltas to be considered as possible dependencies. Typically you only want to consider the deltas that make up the current version. This is decide which transaction to depend on, if a delta is contained by multiple transactions. If this argument is left undefined, then an error will be thrown if one of the deltas is contained by multiple transactions.
  421. export function findTxDependencies(deltas: Delta[], candidates?: Set<Delta>): [Transaction, string][] {
  422. const txDependencies: Map<Transaction,Set<string>> = new Map();
  423. for (const delta of deltas) {
  424. const dependencies = delta.getDependencies();
  425. for (const [dependency, kind] of dependencies) {
  426. if (!deltas.includes(dependency)) {
  427. const txs = dependency.partOf;
  428. const filteredTxs =
  429. candidates !== undefined
  430. ? txs.filter(tx => candidates!.has(tx))
  431. : txs;
  432. if (filteredTxs.length > 1) {
  433. // This error can never occur when passing a proper 'candidates' argument.
  434. throw new Error("Error: One of the composite's dependencies is contained by multiple composites.");
  435. }
  436. if (filteredTxs.length === 0) {
  437. throw new Error("Assertion failed: delta " + delta.description + " depends on " + dependency.description + " but this dependency could not be found in a composite.");
  438. }
  439. const [tx] = filteredTxs;
  440. const kinds = txDependencies.get(tx) || (() => {
  441. const kinds = new Set<string>();
  442. txDependencies.set(tx, kinds);
  443. return kinds;
  444. })();
  445. kinds.add(kind);
  446. }
  447. }
  448. }
  449. return [...txDependencies.entries()].map(([tx, kinds]) => [tx, [...kinds.values()].join(',')]);
  450. }