-
Notifications
You must be signed in to change notification settings - Fork 36
/
compute-hash-transformer.ts
66 lines (58 loc) · 2.09 KB
/
compute-hash-transformer.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import {assert} from '../asserts';
import * as dag from '../dag/mod';
import * as db from '../db/mod';
import type {Hash} from '../hash';
import type {Value} from '../kv/mod';
import type {MaybePromise} from '../replicache';
export type GatheredChunks = ReadonlyMap<Hash, dag.Chunk>;
export type FixedChunks = ReadonlyMap<Hash, dag.Chunk>;
/**
* This transformer computes the hashes
*/
export class ComputeHashTransformer extends db.BaseTransformer {
private readonly _fixedChunks: Map<Hash, dag.Chunk> = new Map();
private readonly _gatheredChunks: GatheredChunks;
private readonly _hashFunc: (value: Value) => MaybePromise<Hash>;
/**
* @param dagWrite The destination dag.
* @param gatheredChunks The chunks that were gathered on the source dag in
* a previous pass.
*/
constructor(
gatheredChunks: GatheredChunks,
hashFunc: (value: Value) => MaybePromise<Hash>,
) {
super();
this._gatheredChunks = gatheredChunks;
this._hashFunc = hashFunc;
}
get fixedChunks(): FixedChunks {
return this._fixedChunks;
}
override shouldSkip(oldhash: Hash): boolean {
// Skip all chunks that we did not get from the source.
return !this._gatheredChunks.has(oldhash);
}
protected override shouldForceWrite(oldHash: Hash): boolean {
// We want to write the chunk to the destination dag even if the chunk did
// not change because the computed hash on the source is different than the
// one computed on the destination.
return this._gatheredChunks.has(oldHash);
}
override async getChunk(hash: Hash): Promise<dag.Chunk | undefined> {
const gatheredChunk = this._gatheredChunks.get(hash);
// We cannot get here if we did not gather a chunk for this hash.
assert(gatheredChunk !== undefined);
return gatheredChunk;
}
protected override async writeChunk<D extends Value>(
_h: Hash,
data: D,
getRefs: (data: D) => readonly Hash[],
): Promise<Hash> {
const hash = await this._hashFunc(data);
const chunk = dag.createChunkWithHash(hash, data, getRefs(data));
this._fixedChunks.set(hash, chunk);
return hash;
}
}