-
Notifications
You must be signed in to change notification settings - Fork 91
/
Copy pathfilecheckpointer.ts
95 lines (80 loc) · 2.65 KB
/
filecheckpointer.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
/*
* Copyright 2022 IBM All Rights Reserved.
*
* SPDX-License-Identifier: Apache-2.0
*/
import fs from 'node:fs';
import { ChaincodeEvent } from './chaincodeevent';
import { Checkpointer } from './checkpointer';
/**
* Interface to store checkpointer state during file read write operations .
*/
interface CheckpointerState {
blockNumber?: string;
transactionId?: string;
}
export class FileCheckPointer implements Checkpointer {
#path: string;
#blockNumber?: bigint;
#transactionId?: string;
constructor(path: string) {
this.#path = path;
}
async init(): Promise<void> {
await this.#loadFromFile();
await this.#saveToFile();
}
async checkpointBlock(blockNumber: bigint): Promise<void> {
this.#blockNumber = blockNumber + BigInt(1);
this.#transactionId = undefined;
await this.#saveToFile();
}
async checkpointTransaction(blockNumber: bigint, transactionId: string): Promise<void> {
this.#blockNumber = blockNumber;
this.#transactionId = transactionId;
await this.#saveToFile();
}
async checkpointChaincodeEvent(event: ChaincodeEvent): Promise<void> {
await this.checkpointTransaction(event.blockNumber, event.transactionId);
}
getBlockNumber(): bigint | undefined {
return this.#blockNumber;
}
getTransactionId(): string | undefined {
return this.#transactionId;
}
async #loadFromFile(): Promise<void> {
const fileDataBuffer = await this.#readFile();
if (fileDataBuffer) {
const data = fileDataBuffer.toString();
if (data.length !== 0) {
const state = JSON.parse(data) as CheckpointerState;
this.#setState(state);
}
}
}
async #readFile(): Promise<Buffer | undefined> {
try {
return await fs.promises.readFile(this.#path);
// eslint-disable-next-line @typescript-eslint/no-unused-vars
} catch (e) {
// ignore file not exist error.
}
return;
}
#setState(state: CheckpointerState): void {
this.#blockNumber = state.blockNumber != undefined ? BigInt(state.blockNumber) : state.blockNumber;
this.#transactionId = state.transactionId;
}
#getState(): CheckpointerState {
return {
blockNumber: this.#blockNumber?.toString(),
transactionId: this.#transactionId,
};
}
async #saveToFile(): Promise<void> {
const state = this.#getState();
const bufferState = Buffer.from(JSON.stringify(state));
await fs.promises.writeFile(this.#path, bufferState);
}
}