-
Notifications
You must be signed in to change notification settings - Fork 15
/
FileSystemGraphObjectStore.ts
367 lines (321 loc) · 10.8 KB
/
FileSystemGraphObjectStore.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
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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
import { Sema } from 'async-sema';
import pMap from 'p-map';
import {
Entity,
GraphObjectFilter,
GraphObjectIteratee,
Relationship,
GraphObjectStore,
GraphObjectIndexMetadata,
GetIndexMetadataForGraphObjectTypeParams,
IntegrationStep,
} from '@jupiterone/integration-sdk-core';
import { flushDataToDisk } from './flushDataToDisk';
import {
iterateEntityTypeIndex,
iterateRelationshipTypeIndex,
readGraphObjectFile,
} from './indices';
import { InMemoryGraphObjectStore } from '../memory';
import { FlushedEntityData } from '../types';
import { getRootStorageAbsolutePath } from '../../fileSystem';
import { BigMap } from '../../execution/utils/bigMap';
export const DEFAULT_GRAPH_OBJECT_BUFFER_THRESHOLD = 500;
// it is important that this value is set to 1
// to ensure that only one operation can be performed at a time.
const BINARY_SEMAPHORE_CONCURRENCY = 1;
export interface FileSystemGraphObjectStoreParams {
integrationSteps?: IntegrationStep[];
/**
* The maximum number of graph objects that this store can buffer in memory
* before writing to disk. Machines with more memory should consider bumping
* this value up.
*
* Default: 500
*/
graphObjectBufferThreshold?: number;
/**
* Whether the files that are written to disk should be minified or not
*/
prettifyFiles?: boolean;
}
interface GraphObjectIndexMetadataMap {
/**
* Map of _type to GraphObjectIndexMetadata
*/
entities: Map<string, GraphObjectIndexMetadata>;
/**
* Map of _type to GraphObjectIndexMetadata
*/
relationships: Map<string, GraphObjectIndexMetadata>;
}
/**
* TODO: Write this comment to explain why the thing is the way it is
*/
function integrationStepsToGraphObjectIndexMetadataMap(
integrationSteps: IntegrationStep[],
): Map<string, GraphObjectIndexMetadataMap> {
const stepIdToGraphObjectIndexMetadataMap = new Map<
string,
GraphObjectIndexMetadataMap
>();
for (const step of integrationSteps) {
const metadataMap: GraphObjectIndexMetadataMap = {
entities: new Map(),
relationships: new Map(),
};
for (const entityMetadata of step.entities) {
if (entityMetadata.indexMetadata) {
metadataMap.entities.set(
entityMetadata._type,
entityMetadata.indexMetadata,
);
}
}
for (const relationshipMetadata of step.relationships) {
if (relationshipMetadata.indexMetadata) {
metadataMap.relationships.set(
relationshipMetadata._type,
relationshipMetadata.indexMetadata,
);
}
}
stepIdToGraphObjectIndexMetadataMap.set(step.id, metadataMap);
}
return stepIdToGraphObjectIndexMetadataMap;
}
/**
* After entities are flushed from the local in-memory graph object store, most are
* placed on disk. (With the exception of entities whose metadata includes
* `{ indexMetadata: { enabled: false }}`).
*
* This map allows us to more efficiently retrieve those entities using the `findEntity()` method,
* using their file path and index.
*/
type GraphObjectLocationOnDisk = {
graphDataPath: string;
index: number;
};
const ENTITY_LOCATION_ON_DISK_DEFAULT_MAP_KEY_SPACE = 2000000;
export class FileSystemGraphObjectStore implements GraphObjectStore {
private readonly semaphore: Sema;
private readonly localGraphObjectStore = new InMemoryGraphObjectStore();
private readonly graphObjectBufferThreshold: number;
private readonly prettifyFiles: boolean;
private readonly stepIdToGraphObjectIndexMetadataMap: Map<
string,
GraphObjectIndexMetadataMap
>;
private readonly entityOnDiskLocationMap = new BigMap<
string,
GraphObjectLocationOnDisk
>(ENTITY_LOCATION_ON_DISK_DEFAULT_MAP_KEY_SPACE);
constructor(params?: FileSystemGraphObjectStoreParams) {
this.semaphore = new Sema(BINARY_SEMAPHORE_CONCURRENCY);
this.graphObjectBufferThreshold =
params?.graphObjectBufferThreshold ||
DEFAULT_GRAPH_OBJECT_BUFFER_THRESHOLD;
this.prettifyFiles = params?.prettifyFiles || false;
if (params?.integrationSteps) {
this.stepIdToGraphObjectIndexMetadataMap =
integrationStepsToGraphObjectIndexMetadataMap(params.integrationSteps);
}
}
async addEntities(
stepId: string,
newEntities: Entity[],
onEntitiesFlushed?: (entities: Entity[]) => Promise<void>,
) {
await this.localGraphObjectStore.addEntities(stepId, newEntities);
if (
this.localGraphObjectStore.getTotalEntityItemCount() >=
this.graphObjectBufferThreshold
) {
await this.flushEntitiesToDisk(onEntitiesFlushed);
}
}
async addRelationships(
stepId: string,
newRelationships: Relationship[],
onRelationshipsFlushed?: (relationships: Relationship[]) => Promise<void>,
) {
await this.localGraphObjectStore.addRelationships(stepId, newRelationships);
if (
this.localGraphObjectStore.getTotalRelationshipItemCount() >=
this.graphObjectBufferThreshold
) {
await this.flushRelationshipsToDisk(onRelationshipsFlushed);
}
}
/**
* The FileSystemGraphObjectStore first checks to see if the entity exists
* in the InMemoryGraphObjectStore. If not, it then checks to see if it is
* located on disk.
*/
async findEntity(_key: string | undefined): Promise<Entity | undefined> {
if (!_key) return;
const bufferedEntity = await this.localGraphObjectStore.findEntity(_key);
if (bufferedEntity) {
return bufferedEntity;
}
const entityLocationOnDisk = this.entityOnDiskLocationMap.get(_key);
if (!entityLocationOnDisk) return;
const filePath = getRootStorageAbsolutePath(
entityLocationOnDisk.graphDataPath,
);
const { entities } = await readGraphObjectFile<FlushedEntityData>({
filePath,
});
return entities[entityLocationOnDisk.index];
}
async iterateEntities<T extends Entity = Entity>(
filter: GraphObjectFilter,
iteratee: GraphObjectIteratee<T>,
) {
await this.localGraphObjectStore.iterateEntities(filter, iteratee);
await iterateEntityTypeIndex({
type: filter._type,
iteratee,
});
}
async iterateRelationships<T extends Relationship = Relationship>(
filter: GraphObjectFilter,
iteratee: GraphObjectIteratee<T>,
) {
await this.localGraphObjectStore.iterateRelationships(filter, iteratee);
await iterateRelationshipTypeIndex({
type: filter._type,
iteratee,
});
}
async flush(
onEntitiesFlushed?: (entities: Entity[]) => Promise<void>,
onRelationshipsFlushed?: (relationships: Relationship[]) => Promise<void>,
) {
await Promise.all([
this.flushEntitiesToDisk(onEntitiesFlushed),
this.flushRelationshipsToDisk(onRelationshipsFlushed),
]);
}
async flushEntitiesToDisk(
onEntitiesFlushed?: (entities: Entity[]) => Promise<void>,
) {
await this.lockOperation(() =>
pMap(
this.localGraphObjectStore.collectEntitiesByStep(),
async ([stepId, entities]) => {
const indexable = entities.filter((e) => {
const indexMetadata = this.getIndexMetadataForGraphObjectType({
stepId,
_type: e._type,
graphObjectCollectionType: 'entities',
});
if (typeof indexMetadata === 'undefined') {
return true;
}
return indexMetadata.enabled === true;
});
if (indexable.length) {
const graphObjectsToFilePaths = await flushDataToDisk({
storageDirectoryPath: stepId,
collectionType: 'entities',
data: indexable,
pretty: this.prettifyFiles,
});
for (const {
graphDataPath,
collection,
} of graphObjectsToFilePaths) {
for (const [index, e] of collection.entries()) {
this.entityOnDiskLocationMap.set(e._key, {
graphDataPath,
index,
});
}
}
}
this.localGraphObjectStore.flushEntities(entities);
if (onEntitiesFlushed) {
await onEntitiesFlushed(entities);
}
},
),
);
}
async flushRelationshipsToDisk(
onRelationshipsFlushed?: (relationships: Relationship[]) => Promise<void>,
) {
await this.lockOperation(() =>
pMap(
this.localGraphObjectStore.collectRelationshipsByStep(),
async ([stepId, relationships]) => {
const indexable = relationships.filter((r) => {
const indexMetadata = this.getIndexMetadataForGraphObjectType({
stepId,
_type: r._type,
graphObjectCollectionType: 'relationships',
});
if (typeof indexMetadata === 'undefined') {
return true;
}
return indexMetadata.enabled === true;
});
if (indexable.length) {
await flushDataToDisk({
storageDirectoryPath: stepId,
collectionType: 'relationships',
data: indexable,
pretty: this.prettifyFiles,
});
}
this.localGraphObjectStore.flushRelationships(relationships);
if (onRelationshipsFlushed) {
await onRelationshipsFlushed(relationships);
}
},
),
);
}
getIndexMetadataForGraphObjectType({
stepId,
_type,
graphObjectCollectionType,
}: GetIndexMetadataForGraphObjectTypeParams):
| GraphObjectIndexMetadata
| undefined {
if (!this.stepIdToGraphObjectIndexMetadataMap) {
return undefined;
}
const map = this.stepIdToGraphObjectIndexMetadataMap.get(stepId);
return map && map[graphObjectCollectionType].get(_type);
}
/**
* This function is ensures that only one input operation can
* happen at a time by utilizing a binary semaphore (lock/unlock).
*
* This is used by `flushEntitiesToDisk` and
* `flushRelationshipsToDisk` to ensure that consumers of this
* object store wait until all of the currently staged data has been
* written to disk.
*
* Waiting for all data to be flushed is important for
* maintaining step execution order when
* flushing data via the `jobState` object.
*
* Without some sort of locking mechanism, one step (let's say, step A)
* could have another step (step B) begin the work of flushing
* it's data to disk. To prevent duplicate data from being flushed,
* step B's flush would "claim" the data to write and remove it from
* the in memory store. Step A would see that there's no work to do
* and prematurely end, causing the next step to start up before the
* data it depends on is present on disk.
*/
private async lockOperation<T>(operation: () => Promise<T>) {
await this.semaphore.acquire();
try {
await operation();
} finally {
this.semaphore.release();
}
}
}