/
entities.ts
305 lines (274 loc) · 10.3 KB
/
entities.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
import {
MongoClient,
Db,
Collection,
GridFSBucket,
Document,
HostAddress
} from '../../../src/index';
import { ReadConcern } from '../../../src/read_concern';
import { WriteConcern } from '../../../src/write_concern';
import { ReadPreference } from '../../../src/read_preference';
import { ClientSession } from '../../../src/sessions';
import { ChangeStream } from '../../../src/change_stream';
import type { ClientEntity, EntityDescription } from './schema';
import type {
CommandFailedEvent,
CommandStartedEvent,
CommandSucceededEvent
} from '../../../src/cmap/command_monitoring_events';
import { patchCollectionOptions, patchDbOptions } from './unified-utils';
import { expect } from 'chai';
import { TestConfiguration } from './runner';
interface UnifiedChangeStream extends ChangeStream {
eventCollector: InstanceType<typeof import('../../tools/utils')['EventCollector']>;
}
export type CommandEvent = CommandStartedEvent | CommandSucceededEvent | CommandFailedEvent;
function serverApiConfig() {
if (process.env.MONGODB_API_VERSION) {
return { version: process.env.MONGODB_API_VERSION };
}
}
function getClient(address) {
const serverApi = serverApiConfig();
return new MongoClient(`mongodb://${address}`, serverApi ? { serverApi } : {});
}
export class UnifiedMongoClient extends MongoClient {
events: CommandEvent[];
failPoints: Document[];
ignoredEvents: string[];
observedEvents: ('commandStarted' | 'commandSucceeded' | 'commandFailed')[];
static EVENT_NAME_LOOKUP = {
commandStartedEvent: 'commandStarted',
commandSucceededEvent: 'commandSucceeded',
commandFailedEvent: 'commandFailed'
} as const;
constructor(url: string, description: ClientEntity) {
super(url, {
monitorCommands: true,
...description.uriOptions,
serverApi: description.serverApi ? description.serverApi : serverApiConfig()
});
this.events = [];
this.failPoints = [];
this.ignoredEvents = [
...(description.ignoreCommandMonitoringEvents ?? []),
'configureFailPoint'
];
// apm
this.observedEvents = (description.observeEvents ?? []).map(
e => UnifiedMongoClient.EVENT_NAME_LOOKUP[e]
);
for (const eventName of this.observedEvents) {
this.on(eventName, this.pushEvent);
}
}
// NOTE: pushEvent must be an arrow function
pushEvent: (e: CommandEvent) => void = e => {
if (!this.ignoredEvents.includes(e.commandName)) {
this.events.push(e);
}
};
/** Disables command monitoring for the client and returns a list of the captured events. */
stopCapturingEvents(): CommandEvent[] {
for (const eventName of this.observedEvents) {
this.off(eventName, this.pushEvent);
}
return this.events;
}
}
export class FailPointMap extends Map<string, Document> {
async enableFailPoint(
addressOrClient: HostAddress | UnifiedMongoClient,
failPoint: Document
): Promise<Document> {
let client: MongoClient;
let address: string;
if (addressOrClient instanceof MongoClient) {
client = addressOrClient;
address = client.topology.s.seedlist.join(',');
} else {
// create a new client
address = addressOrClient.toString();
client = getClient(address);
await client.connect();
}
const admin = client.db('admin');
const result = await admin.command(failPoint);
if (!(addressOrClient instanceof MongoClient)) {
// we created this client
await client.close();
}
expect(result).to.have.property('ok', 1);
this.set(address, failPoint.configureFailPoint);
return result;
}
async disableFailPoints(): Promise<void> {
const entries = Array.from(this.entries());
await Promise.all(
entries.map(async ([hostAddress, configureFailPoint]) => {
const client = getClient(hostAddress);
await client.connect();
const admin = client.db('admin');
const result = await admin.command({ configureFailPoint, mode: 'off' });
expect(result).to.have.property('ok', 1);
await client.close();
})
);
}
}
export type Entity =
| UnifiedMongoClient
| Db
| Collection
| ClientSession
| UnifiedChangeStream
| GridFSBucket
| Document; // Results from operations
export type EntityCtor =
| typeof UnifiedMongoClient
| typeof Db
| typeof Collection
| typeof ClientSession
| typeof ChangeStream
| typeof GridFSBucket;
export type EntityTypeId = 'client' | 'db' | 'collection' | 'session' | 'bucket' | 'stream';
const ENTITY_CTORS = new Map<EntityTypeId, EntityCtor>();
ENTITY_CTORS.set('client', UnifiedMongoClient);
ENTITY_CTORS.set('db', Db);
ENTITY_CTORS.set('collection', Collection);
ENTITY_CTORS.set('session', ClientSession);
ENTITY_CTORS.set('bucket', GridFSBucket);
ENTITY_CTORS.set('stream', ChangeStream);
export class EntitiesMap<E = Entity> extends Map<string, E> {
failPoints: FailPointMap;
constructor(entries?: readonly (readonly [string, E])[] | null) {
super(entries);
this.failPoints = new FailPointMap();
}
mapOf(type: 'client'): EntitiesMap<UnifiedMongoClient>;
mapOf(type: 'db'): EntitiesMap<Db>;
mapOf(type: 'collection'): EntitiesMap<Collection>;
mapOf(type: 'session'): EntitiesMap<ClientSession>;
mapOf(type: 'bucket'): EntitiesMap<GridFSBucket>;
mapOf(type: 'stream'): EntitiesMap<UnifiedChangeStream>;
mapOf(type: EntityTypeId): EntitiesMap<Entity> {
const ctor = ENTITY_CTORS.get(type);
if (!ctor) {
throw new Error(`Unknown type ${type}`);
}
return new EntitiesMap(Array.from(this.entries()).filter(([, e]) => e instanceof ctor));
}
getEntity(type: 'client', key: string, assertExists?: boolean): UnifiedMongoClient;
getEntity(type: 'db', key: string, assertExists?: boolean): Db;
getEntity(type: 'collection', key: string, assertExists?: boolean): Collection;
getEntity(type: 'session', key: string, assertExists?: boolean): ClientSession;
getEntity(type: 'bucket', key: string, assertExists?: boolean): GridFSBucket;
getEntity(type: 'stream', key: string, assertExists?: boolean): UnifiedChangeStream;
getEntity(type: EntityTypeId, key: string, assertExists = true): Entity {
const entity = this.get(key);
if (!entity) {
if (assertExists) throw new Error(`Entity '${key}' does not exist`);
return;
}
const ctor = ENTITY_CTORS.get(type);
if (!ctor) {
throw new Error(`Unknown type ${type}`);
}
if (!(entity instanceof ctor)) {
throw new Error(`${key} is not an instance of ${type}`);
}
return entity;
}
async cleanup(): Promise<void> {
await this.failPoints.disableFailPoints();
for (const [, client] of this.mapOf('client')) {
await client.close();
}
for (const [, session] of this.mapOf('session')) {
await session.endSession();
}
this.clear();
}
static async createEntities(
config: TestConfiguration,
entities?: EntityDescription[]
): Promise<EntitiesMap> {
const map = new EntitiesMap();
for (const entity of entities ?? []) {
if ('client' in entity) {
const useMultipleMongoses =
config.topologyType === 'Sharded' && entity.client.useMultipleMongoses;
const uri = config.url({ useMultipleMongoses });
const client = new UnifiedMongoClient(uri, entity.client);
await client.connect();
map.set(entity.client.id, client);
} else if ('database' in entity) {
const client = map.getEntity('client', entity.database.client);
const db = client.db(
entity.database.databaseName,
patchDbOptions(entity.database.databaseOptions)
);
map.set(entity.database.id, db);
} else if ('collection' in entity) {
const db = map.getEntity('db', entity.collection.database);
const collection = db.collection(
entity.collection.collectionName,
patchCollectionOptions(entity.collection.collectionOptions)
);
map.set(entity.collection.id, collection);
} else if ('session' in entity) {
const client = map.getEntity('client', entity.session.client);
const options = Object.create(null);
if (entity.session.sessionOptions?.causalConsistency) {
options.causalConsistency = entity.session.sessionOptions?.causalConsistency;
}
if (entity.session.sessionOptions?.snapshot) {
options.snapshot = entity.session.sessionOptions.snapshot;
}
if (entity.session.sessionOptions?.defaultTransactionOptions) {
options.defaultTransactionOptions = Object.create(null);
const defaultOptions = entity.session.sessionOptions.defaultTransactionOptions;
if (defaultOptions.readConcern) {
options.defaultTransactionOptions.readConcern = ReadConcern.fromOptions(
defaultOptions.readConcern
);
}
if (defaultOptions.writeConcern) {
options.defaultTransactionOptions.writeConcern = WriteConcern.fromOptions(
defaultOptions
);
}
if (defaultOptions.readPreference) {
options.defaultTransactionOptions.readPreference = ReadPreference.fromOptions(
defaultOptions.readPreference
);
}
if (typeof defaultOptions.maxCommitTimeMS === 'number') {
options.defaultTransactionOptions.maxCommitTimeMS = defaultOptions.maxCommitTimeMS;
}
}
const session = client.startSession(options);
map.set(entity.session.id, session);
} else if ('bucket' in entity) {
const db = map.getEntity('db', entity.bucket.database);
const options = Object.create(null);
if (entity.bucket.bucketOptions?.bucketName) {
options.bucketName = entity.bucket.bucketOptions?.bucketName;
}
if (entity.bucket.bucketOptions?.chunkSizeBytes) {
options.chunkSizeBytes = entity.bucket.bucketOptions?.chunkSizeBytes;
}
if (entity.bucket.bucketOptions?.readPreference) {
options.readPreference = entity.bucket.bucketOptions?.readPreference;
}
map.set(entity.bucket.id, new GridFSBucket(db, options));
} else if ('stream' in entity) {
throw new Error(`Unsupported Entity ${JSON.stringify(entity)}`);
} else {
throw new Error(`Unsupported Entity ${JSON.stringify(entity)}`);
}
}
return map;
}
}