-
Notifications
You must be signed in to change notification settings - Fork 14
/
table.js
241 lines (187 loc) · 6.53 KB
/
table.js
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
// we hash (sha-1 // or that new faster hash) the key and createa a <hash>.json file to store the record
import path from 'path';
import fs from 'fs';
import {discohash} from 'bebb4185';
const UNKNOWN_FAILURE = key => `DB operation failed for key ${key}. No reason given`;
const INTERNAL_RECORDS = new Set([
'tableInfo.json',
'indexes.json'
]);
export class Table {
constructor(tableInfo) {
if ( ! tableInfo ) {
throw new TypeError(`Table constructor specify tableInfo`);
}
if ( ! new.target ) {
throw new TypeError('Table must be called with new');
}
this.tableInfo = tableInfo;
this.base = path.resolve(path.dirname(tableInfo.tableBase));
}
put(key, record, greenlights = null) {
const keyHash = discohash(key).toString(16);
const keyFileName = path.resolve(this.base, `${keyHash}.json`);
const recordString = JSON.stringify(record,null,2);
guardGreenLights(greenlights, {key, record, recordString});
fs.writeFileSync(keyFileName, recordString);
}
get(key, greenlights = null) {
const keyHash = discohash(key).toString(16);
const keyFileName = path.resolve(this.base, `${keyHash}.json`);
const record = JSON.parse(fs.readFileSync(keyFileName).toString());
guardGreenLights(greenlights, {key, record});
return record;
}
getAll(greenlights = null) {
const dir = fs.opendirSync(this.base);
const list = [];
let ent = dir.readSync();
while(ent) {
if ( ent.isFile() && !INTERNAL_RECORDS.has(ent.name) ) {
const keyFileName = path.resolve(this.base, ent.name);
list.push(JSON.parse(fs.readFileSync(keyFileName).toString()));
}
ent = dir.readSync();
}
dir.close();
guardGreenLights(greenlights, {list});
return list;
}
}
export class IndexedTable extends Table {
put(key, record, greenlights = null) {
let oldRecord;
try {
oldRecord = this.get(key);
} catch(e) {
oldRecord = undefined;
}
super.put(key, record, greenlights);
const {indexes,indexBase} = this.tableInfo;
let indexesUpdated = 0;
for( const prop of indexes ) {
const value = record[prop];
let oldValue;
if ( oldRecord ) oldValue = oldRecord[prop];
if ( oldValue != value ) {
const propIndex = indexBase[prop];
if ( deindex(oldValue, key, propIndex) ) {
indexesUpdated ++;
}
if ( index(value, key, propIndex) ) {
indexesUpdated ++;
}
}
}
return indexesUpdated;
}
getAllMatchingKeysFromIndex(propName, value) {
const {indexes,indexBase} = this.tableInfo;
if ( !(new Set(indexes)).has(propName) ) {
throw new TypeError(`Property ${propName} is not indexed for table ${this.tableInfo.name}`);
}
const propIndex = indexBase[propName];
const valueHash = discohash(value).toString(16);
const value64 = Buffer.from(value+'').toString('base64');
const indexRecordFileName = path.resolve(propIndex, `${valueHash}.json`);
let indexRecord;
try {
indexRecord = JSON.parse(fs.readFileSync(indexRecordFileName).toString());
} catch(e) {
indexRecord = {};
}
if ( ! indexRecord[value64] ) {
return [];
} else {
return indexRecord[value64];
}
}
getAllMatchingRecordsFromIndex(propName, value) {
const matchingKeys = this.getAllMatchingKeysFromIndex(propName, value);
const matchingRecords = [];
for( const key of matchingKeys ) {
try {
matchingRecords.push([key, this.get(key)]);
} catch(e) {
console.info(`Key ${key} deleted from table ${this.tableInfo.name}`);
matchingRecords.push([key, null]);
}
}
return matchingRecords;
}
}
function index(value, key, propIndex) {
const valueHash = discohash(value).toString(16);
const value64 = Buffer.from(value+'').toString('base64');
const indexRecordFileName = path.resolve(propIndex, `${valueHash}.json`);
let indexRecord;
let indexUpdated = false;
try {
indexRecord = JSON.parse(fs.readFileSync(indexRecordFileName).toString());
} catch(e) {
indexRecord = {};
}
if ( ! indexRecord[value64] ) {
indexRecord[value64] = [];
}
const keysWithValue = new Set(indexRecord[value64]);
if ( ! keysWithValue.has(key) ) {
keysWithValue.add(key);
indexRecord[value64] = [...keysWithValue.keys()];
fs.writeFileSync(indexRecordFileName, JSON.stringify(indexRecord,null,2));
indexUpdated = true;
}
return indexUpdated;
}
function deindex(value, key, propIndex) {
const valueHash = discohash(value).toString(16);
const value64 = Buffer.from(value+'').toString('base64');
const indexRecordFileName = path.resolve(propIndex, `${valueHash}.json`);
let indexRecord;
let indexUpdated = false;
try {
indexRecord = JSON.parse(fs.readFileSync(indexRecordFileName).toString());
} catch(e) {
indexRecord = {};
}
if ( ! indexRecord[value64] ) {
indexRecord[value64] = [];
}
const keysWithValue = new Set(indexRecord[value64]);
if ( keysWithValue.has(key) ) {
keysWithValue.delete(key);
indexRecord[value64] = [...keysWithValue.keys()];
fs.writeFileSync(indexRecordFileName, JSON.stringify(indexRecord,null,2));
indexUpdated = true;
}
return indexUpdated;
}
function guardGreenLights(greenlights, {key:key = undefined, record:record = undefined, list:list = undefined, recordString:recordString = ''}) {
// waiting for node 14
//const exists = greenlights ?? false;
const exists = !!greenlights;
if ( exists ) {
if ( greenlights instanceof Function ) {
const result = greenlights({key, record, recordString, list});
if ( !result.allow ) {
throw result.reason || UNKNOWN_FAILURE(key);
}
} else if ( Array.isArray(greenlights) ) {
const results = greenlights.map(func => func({key, record, recordString, list}));
const okay = results.every(result => result.allow);
if ( ! okay ) {
throw results.filter(result => !result.allow).map(({reason}) => reason || UNKNOWN_FAILURE(key));
}
} else if ( greenlights.evaluator ) {
const results = greenlights.evaluations.map(func => func({key, record, recordString, list}));
const signal = greenlights.evaluator(greenlights.evaluations, {key, record, recordString, list});
if ( !signal.allow ) {
throw {results, reasons: signal.reasons};
}
} else {
throw `If provided greenlights functions parameter must be either:
single function, array of functions, or evaluator object.
Was ${greenlights}`;
}
}
}