@playwright-orchestrator/mongo 1.2.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,7 @@
1
+ import { Binary } from 'mongodb';
2
+ export declare function generateTestId(runId: string, order: number): Binary;
3
+ export declare function generateRunId(runId: string): Binary;
4
+ export declare function parseTestId(testId: Binary): {
5
+ runId: string;
6
+ order: number;
7
+ };
@@ -0,0 +1,18 @@
1
+ import { Binary } from 'mongodb';
2
+ import * as uuid from 'uuid';
3
+ export function generateTestId(runId, order) {
4
+ const binaryRunId = uuid.parse(runId);
5
+ const orderBytes = new Uint8Array(2);
6
+ orderBytes[0] = (order >> 8) & 0xff;
7
+ orderBytes[1] = order & 0xff;
8
+ const combined = new Uint8Array([...binaryRunId, ...orderBytes]);
9
+ return new Binary(combined, Binary.SUBTYPE_USER_DEFINED);
10
+ }
11
+ export function generateRunId(runId) {
12
+ return new Binary(uuid.parse(runId));
13
+ }
14
+ export function parseTestId(testId) {
15
+ const runId = uuid.stringify(testId.buffer.slice(0, 16));
16
+ const order = (testId.buffer[16] << 8) + testId.buffer[17];
17
+ return { runId, order };
18
+ }
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { Command } from '@commander-js/extra-typings';
2
- import { CreateArgs } from './create-args.js';
3
- import { MongoDbAdapter } from './mongo-db-adapter.js';
4
- export declare function factory(args: CreateArgs): Promise<MongoDbAdapter>;
2
+ import { Container } from 'inversify';
3
+ import type { CreateArgs } from './create-args.js';
4
+ export declare function register(container: Container, options: CreateArgs): void;
5
5
  export declare function createOptions(command: Command): void;
6
6
  export declare const description = "MongoDB storage adapter";
package/dist/index.js CHANGED
@@ -1,7 +1,18 @@
1
1
  import { Option } from '@commander-js/extra-typings';
2
+ import { SYMBOLS } from '@playwright-orchestrator/core';
2
3
  import { MongoDbAdapter } from './mongo-db-adapter.js';
3
- export async function factory(args) {
4
- return new MongoDbAdapter(args);
4
+ import { MongoShardHandler } from './mongo-shard-handler.js';
5
+ import { MongoInitializer } from './mongo-initializer.js';
6
+ import { MongoTestRunCreator } from './mongo-test-run-creator.js';
7
+ import { MongoConnection } from './mongo-connection.js';
8
+ import { MONGO_CONFIG, MONGO_CONNECTION } from './symbols.js';
9
+ export function register(container, options) {
10
+ container.bind(MONGO_CONFIG).toConstantValue(options);
11
+ container.bind(MONGO_CONNECTION).to(MongoConnection).inSingletonScope();
12
+ container.bind(SYMBOLS.Adapter).to(MongoDbAdapter).inSingletonScope();
13
+ container.bind(SYMBOLS.ShardHandler).to(MongoShardHandler).inSingletonScope();
14
+ container.bind(SYMBOLS.Initializer).to(MongoInitializer).inSingletonScope();
15
+ container.bind(SYMBOLS.TestRunCreator).to(MongoTestRunCreator).inSingletonScope();
5
16
  }
6
17
  export function createOptions(command) {
7
18
  command
@@ -0,0 +1,8 @@
1
+ import type { CreateArgs } from './create-args.js';
2
+ import { MongoClient, Db } from 'mongodb';
3
+ export declare class MongoConnection {
4
+ readonly client: MongoClient;
5
+ readonly db: Db;
6
+ constructor(args: CreateArgs);
7
+ dispose(): Promise<void>;
8
+ }
@@ -0,0 +1,48 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __metadata = (this && this.__metadata) || function (k, v) {
8
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
9
+ };
10
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
11
+ return function (target, key) { decorator(target, key, paramIndex); }
12
+ };
13
+ import { injectable, inject, preDestroy } from 'inversify';
14
+ import { MongoClient } from 'mongodb';
15
+ import { MONGO_CONFIG } from './symbols.js';
16
+ let MongoConnection = class MongoConnection {
17
+ client;
18
+ db;
19
+ constructor(args) {
20
+ const { connectionString, db, tls, tlsCA, tlsKey, tlsKeyPassword, tlsPassphrase, tlsAllowInvalidCertificates, tlsAllowInvalidHostnames, tlsInsecure, } = args;
21
+ this.client = new MongoClient(connectionString, {
22
+ tls,
23
+ tlsCAFile: tlsCA,
24
+ tlsCertificateKeyFile: tlsKey,
25
+ tlsCertificateKeyFilePassword: tlsKeyPassword,
26
+ passphrase: tlsPassphrase,
27
+ tlsAllowInvalidCertificates,
28
+ tlsAllowInvalidHostnames,
29
+ tlsInsecure,
30
+ });
31
+ this.db = this.client.db(db);
32
+ }
33
+ async dispose() {
34
+ await this.client.close();
35
+ }
36
+ };
37
+ __decorate([
38
+ preDestroy(),
39
+ __metadata("design:type", Function),
40
+ __metadata("design:paramtypes", []),
41
+ __metadata("design:returntype", Promise)
42
+ ], MongoConnection.prototype, "dispose", null);
43
+ MongoConnection = __decorate([
44
+ injectable(),
45
+ __param(0, inject(MONGO_CONFIG)),
46
+ __metadata("design:paramtypes", [Object])
47
+ ], MongoConnection);
48
+ export { MongoConnection };
@@ -1,30 +1,17 @@
1
- import { TestItem, Adapter, TestRunConfig, TestRunReport, ResultTestParams, SaveTestRunParams } from '@playwright-orchestrator/core';
2
- import { CreateArgs } from './create-args.js';
3
- export declare class MongoDbAdapter extends Adapter {
1
+ import { BaseAdapter, TestRunReport, SaveTestResultParams } from '@playwright-orchestrator/core';
2
+ import type { CreateArgs } from './create-args.js';
3
+ import { MongoConnection } from './mongo-connection.js';
4
+ export declare class MongoDbAdapter extends BaseAdapter {
4
5
  private readonly runsCollection;
5
6
  private readonly testsCollection;
6
7
  private readonly testsInfoCollection;
7
- private readonly debug;
8
- private readonly db;
9
- private readonly client;
10
- constructor(args: CreateArgs);
11
- getNextTest(runId: string, config: TestRunConfig): Promise<TestItem | undefined>;
12
- finishTest(params: ResultTestParams): Promise<void>;
13
- failTest(params: ResultTestParams): Promise<void>;
14
- private updateTest;
15
- saveTestRun({ testRun, runId, args, historyWindow }: SaveTestRunParams): Promise<void>;
16
- private loadTestInfo;
17
- initialize(): Promise<void>;
18
- startShard(runId: string): Promise<TestRunConfig>;
19
- private generateTestIdQuery;
20
- private mapDbToTestRunConfig;
21
- finishShard(runId: string): Promise<void>;
22
- dispose(): Promise<void>;
8
+ private readonly connection;
9
+ constructor({ collectionNamePrefix }: CreateArgs, connection: MongoConnection);
23
10
  getReportData(runId: string): Promise<TestRunReport>;
11
+ getTestEma(testId: string): Promise<number>;
12
+ saveTestResult({ runId, test, item, historyWindow, newEma }: SaveTestResultParams): Promise<void>;
24
13
  private get runs();
25
14
  private get tests();
26
15
  private get testInfo();
27
- private generateTestId;
28
- private generateRunId;
29
- private parseTestId;
16
+ private generateTestIdQuery;
30
17
  }
@@ -1,231 +1,52 @@
1
- import { Adapter, RunStatus, TestStatus, } from '@playwright-orchestrator/core';
2
- import { MongoClient, Binary } from 'mongodb';
3
- import * as uuid from 'uuid';
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __metadata = (this && this.__metadata) || function (k, v) {
8
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
9
+ };
10
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
11
+ return function (target, key) { decorator(target, key, paramIndex); }
12
+ };
13
+ import { BaseAdapter, TestStatus, } from '@playwright-orchestrator/core';
14
+ import { injectable, inject } from 'inversify';
15
+ import { MongoConnection } from './mongo-connection.js';
16
+ import { MONGO_CONFIG, MONGO_CONNECTION } from './symbols.js';
17
+ import { generateTestId, generateRunId } from './helpers.js';
4
18
  const MAX_ORDER = 0b1111111111111111;
5
- export class MongoDbAdapter extends Adapter {
19
+ let MongoDbAdapter = class MongoDbAdapter extends BaseAdapter {
6
20
  runsCollection;
7
21
  testsCollection;
8
22
  testsInfoCollection;
9
- debug;
10
- db;
11
- client;
12
- constructor(args) {
13
- const { connectionString, collectionNamePrefix, db, tls, tlsCA, tlsKey, tlsPassphrase, tlsAllowInvalidCertificates, tlsAllowInvalidHostnames, tlsInsecure, tlsKeyPassword, debug, } = args;
23
+ connection;
24
+ constructor({ collectionNamePrefix }, connection) {
14
25
  super();
15
- this.client = new MongoClient(connectionString, {
16
- tls,
17
- tlsCAFile: tlsCA,
18
- tlsCertificateKeyFile: tlsKey,
19
- tlsCertificateKeyFilePassword: tlsKeyPassword,
20
- passphrase: tlsPassphrase,
21
- tlsAllowInvalidCertificates,
22
- tlsAllowInvalidHostnames,
23
- tlsInsecure,
24
- });
25
- this.db = this.client.db(db);
26
+ this.connection = connection;
26
27
  this.runsCollection = `${collectionNamePrefix}_test_runs`;
27
28
  this.testsCollection = `${collectionNamePrefix}_tests`;
28
29
  this.testsInfoCollection = `${collectionNamePrefix}_tests_info`;
29
- this.debug = debug ?? false;
30
- }
31
- async getNextTest(runId, config) {
32
- const result = await this.tests.findOneAndUpdate(this.generateTestIdQuery(runId, TestStatus.Ready), {
33
- $set: {
34
- updated: new Date(),
35
- status: TestStatus.Ongoing,
36
- },
37
- });
38
- if (!result)
39
- return undefined;
40
- const { file, line, column, project, timeout } = result;
41
- const { order } = this.parseTestId(result._id);
42
- return {
43
- file,
44
- position: `${line}:${column}`,
45
- project,
46
- timeout,
47
- order,
48
- };
49
- }
50
- async finishTest(params) {
51
- await this.updateTest(TestStatus.Passed, params);
52
- }
53
- async failTest(params) {
54
- await this.updateTest(TestStatus.Failed, params);
55
- }
56
- async updateTest(status, { test, runId, testResult, config }) {
57
- const { order } = test;
58
- const { duration, title } = testResult;
59
- const testId = this.generateTestId(runId, order);
60
- const testInfoId = this.getTestId({ ...test, ...testResult });
61
- const testInfo = (await this.testInfo.findOne({ _id: testInfoId }));
62
- this.testInfo.updateOne({ _id: testInfoId }, {
63
- $set: {
64
- ema: this.calculateEMA(duration, testInfo.ema, config.historyWindow),
65
- },
66
- // @ts-ignore
67
- $push: {
68
- history: {
69
- $each: [
70
- {
71
- duration,
72
- status,
73
- updated: new Date(),
74
- },
75
- ],
76
- $slice: -config.historyWindow,
77
- },
78
- },
79
- });
80
- await this.tests.updateOne({ _id: testId }, {
81
- $set: {
82
- status,
83
- updated: new Date(),
84
- report: {
85
- duration: duration,
86
- title: title,
87
- ema: testInfo.ema,
88
- fails: testInfo.history.filter((h) => h.status === TestStatus.Failed).length,
89
- lastSuccessfulRun: testInfo.history.findLast((h) => h.status === TestStatus.Passed)?.updated,
90
- },
91
- },
92
- });
93
- }
94
- async saveTestRun({ testRun, runId, args, historyWindow }) {
95
- let tests = this.transformTestRunToItems(testRun.testRun);
96
- const testInfos = await this.loadTestInfo(tests);
97
- tests = this.sortTests(tests, testInfos, { historyWindow });
98
- const run = {
99
- _id: this.generateRunId(runId),
100
- status: RunStatus.Created,
101
- config: testRun.config,
102
- args,
103
- historyWindow,
104
- updated: new Date(),
105
- };
106
- await this.runs.insertOne(run);
107
- await this.tests.insertMany(tests.map(({ file, order, position, project, timeout }) => {
108
- const [line, column] = position.split(':').map(Number);
109
- return {
110
- _id: this.generateTestId(runId, order),
111
- file,
112
- project,
113
- timeout,
114
- line,
115
- column,
116
- status: TestStatus.Ready,
117
- updated: new Date(),
118
- ...(this.debug ? { runId, order } : {}),
119
- };
120
- }));
121
- }
122
- async loadTestInfo(tests) {
123
- const testInfoMap = new Map();
124
- for (const { testId } of tests) {
125
- if (!testInfoMap.has(testId)) {
126
- const item = await this.testInfo.findOneAndUpdate({ _id: testId }, {
127
- $setOnInsert: {
128
- _id: testId,
129
- create: new Date(),
130
- ema: 0,
131
- history: [],
132
- },
133
- }, { upsert: true, returnDocument: 'after' });
134
- testInfoMap.set(testId, {
135
- ema: item.ema,
136
- fails: item.history.filter((h) => h.status === TestStatus.Failed).length,
137
- });
138
- }
139
- }
140
- return testInfoMap;
141
- }
142
- async initialize() {
143
- const collections = await this.db.collections();
144
- const set = new Set(collections.map((c) => c.collectionName));
145
- if (!set.has(this.runsCollection)) {
146
- await this.db.createCollection(this.runsCollection);
147
- }
148
- if (!set.has(this.testsCollection)) {
149
- const collection = await this.db.createCollection(this.testsCollection);
150
- await collection.createIndex({ status: 1 });
151
- }
152
- if (!set.has(this.testsInfoCollection)) {
153
- await this.db.createCollection(this.testsInfoCollection);
154
- }
155
- }
156
- async startShard(runId) {
157
- const now = new Date();
158
- const run = await this.runs.findOneAndUpdate({ _id: this.generateRunId(runId) }, [
159
- {
160
- $set: {
161
- status: {
162
- $cond: {
163
- if: { $in: ['$status', [RunStatus.Created]] },
164
- then: RunStatus.Run,
165
- else: RunStatus.RepeatRun,
166
- },
167
- },
168
- updated: now,
169
- },
170
- },
171
- ]);
172
- if (!run) {
173
- throw new Error(`Run ${runId} not found`);
174
- }
175
- const { status: statusBefore } = run;
176
- if (statusBefore === RunStatus.Created || statusBefore === RunStatus.Finished) {
177
- await this.tests.updateMany(this.generateTestIdQuery(runId, TestStatus.Failed), {
178
- $set: {
179
- status: TestStatus.Ready,
180
- updated: now,
181
- },
182
- });
183
- }
184
- return this.mapDbToTestRunConfig(run);
185
- }
186
- generateTestIdQuery(runId, ...statuses) {
187
- return {
188
- _id: {
189
- $gte: this.generateTestId(runId, 0),
190
- $lt: this.generateTestId(runId, MAX_ORDER),
191
- },
192
- status: { $in: statuses },
193
- };
194
- }
195
- mapDbToTestRunConfig(run) {
196
- const { args, config, status, updated, historyWindow } = run;
197
- return { ...config, args, historyWindow, status, updated: updated.getTime() };
198
- }
199
- async finishShard(runId) {
200
- await this.runs.updateOne({ _id: uuid.parse(runId) }, {
201
- $set: {
202
- status: RunStatus.Finished,
203
- updated: new Date(),
204
- },
205
- });
206
- }
207
- async dispose() {
208
- await this.client.close();
209
30
  }
210
31
  async getReportData(runId) {
211
- const run = await this.runs.findOne({ _id: this.generateRunId(runId) });
32
+ const run = await this.runs.findOne({ _id: generateRunId(runId) });
212
33
  if (!run) {
213
34
  throw new Error(`Run ${runId} not found`);
214
35
  }
215
- const config = this.mapDbToTestRunConfig(run);
36
+ const config = run.config;
216
37
  const tests = await this.tests
217
38
  .find(this.generateTestIdQuery(runId, TestStatus.Failed, TestStatus.Passed))
218
39
  .toArray();
219
40
  return {
220
41
  runId,
221
42
  config,
222
- tests: tests.map(({ file, line, column, project, status, report }) => {
43
+ tests: tests.map(({ file, line, column, status, report, projects }) => {
223
44
  const position = `${line}:${column}`;
224
45
  const { duration, fails, title, lastSuccessfulRun, ema } = report;
225
46
  return {
226
47
  file,
227
48
  position,
228
- project,
49
+ projects,
229
50
  status,
230
51
  title,
231
52
  duration,
@@ -236,29 +57,67 @@ export class MongoDbAdapter extends Adapter {
236
57
  }),
237
58
  };
238
59
  }
60
+ async getTestEma(testId) {
61
+ const doc = await this.testInfo.findOne({ _id: testId });
62
+ return doc?.ema ?? 0;
63
+ }
64
+ async saveTestResult({ runId, test, item, historyWindow, newEma }) {
65
+ const updatedDoc = await this.testInfo.findOneAndUpdate({ _id: test.testId }, {
66
+ $set: { ema: newEma },
67
+ // @ts-ignore
68
+ $push: {
69
+ history: {
70
+ $each: [{ duration: item.duration, status: item.status, updated: new Date(item.updated) }],
71
+ $slice: -historyWindow,
72
+ },
73
+ },
74
+ }, { returnDocument: 'after' });
75
+ const history = (updatedDoc?.history ?? []).map((h) => ({
76
+ status: h.status,
77
+ duration: h.duration,
78
+ updated: h.updated instanceof Date ? h.updated.getTime() : h.updated,
79
+ }));
80
+ const report = this.buildReport(test, item, newEma, history);
81
+ const testDocId = generateTestId(runId, test.order);
82
+ await this.tests.updateOne({ _id: testDocId }, {
83
+ $set: {
84
+ status: report.status,
85
+ updated: new Date(),
86
+ report: {
87
+ duration: report.duration,
88
+ title: report.title,
89
+ ema: report.averageDuration,
90
+ fails: report.fails,
91
+ lastSuccessfulRun: report.lastSuccessfulRunTimestamp
92
+ ? new Date(report.lastSuccessfulRunTimestamp)
93
+ : undefined,
94
+ },
95
+ },
96
+ });
97
+ }
239
98
  get runs() {
240
- return this.db.collection(this.runsCollection);
99
+ return this.connection.db.collection(this.runsCollection);
241
100
  }
242
101
  get tests() {
243
- return this.db.collection(this.testsCollection);
102
+ return this.connection.db.collection(this.testsCollection);
244
103
  }
245
104
  get testInfo() {
246
- return this.db.collection(this.testsInfoCollection);
247
- }
248
- generateTestId(runId, order) {
249
- const binaryRunId = uuid.parse(runId);
250
- const orderBytes = new Uint8Array(2);
251
- orderBytes[0] = (order >> 8) & 0xff;
252
- orderBytes[1] = order & 0xff;
253
- const combined = new Uint8Array([...binaryRunId, ...orderBytes]);
254
- return new Binary(combined, Binary.SUBTYPE_USER_DEFINED);
255
- }
256
- generateRunId(runId) {
257
- return new Binary(uuid.parse(runId));
105
+ return this.connection.db.collection(this.testsInfoCollection);
258
106
  }
259
- parseTestId(testId) {
260
- const runId = uuid.stringify(testId.buffer.slice(0, 16));
261
- const order = (testId.buffer[16] << 8) + testId.buffer[17];
262
- return { runId, order };
107
+ generateTestIdQuery(runId, ...statuses) {
108
+ return {
109
+ _id: {
110
+ $gte: generateTestId(runId, 0),
111
+ $lt: generateTestId(runId, MAX_ORDER),
112
+ },
113
+ status: { $in: statuses },
114
+ };
263
115
  }
264
- }
116
+ };
117
+ MongoDbAdapter = __decorate([
118
+ injectable(),
119
+ __param(0, inject(MONGO_CONFIG)),
120
+ __param(1, inject(MONGO_CONNECTION)),
121
+ __metadata("design:paramtypes", [Object, MongoConnection])
122
+ ], MongoDbAdapter);
123
+ export { MongoDbAdapter };
@@ -0,0 +1,9 @@
1
+ import type { Initializer } from '@playwright-orchestrator/core';
2
+ import type { CreateArgs } from './create-args.js';
3
+ import { MongoConnection } from './mongo-connection.js';
4
+ export declare class MongoInitializer implements Initializer {
5
+ private readonly config;
6
+ private readonly connection;
7
+ constructor(config: CreateArgs, connection: MongoConnection);
8
+ initialize(): Promise<void>;
9
+ }
@@ -0,0 +1,45 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __metadata = (this && this.__metadata) || function (k, v) {
8
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
9
+ };
10
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
11
+ return function (target, key) { decorator(target, key, paramIndex); }
12
+ };
13
+ import { injectable, inject } from 'inversify';
14
+ import { MongoConnection } from './mongo-connection.js';
15
+ import { MONGO_CONFIG, MONGO_CONNECTION } from './symbols.js';
16
+ let MongoInitializer = class MongoInitializer {
17
+ config;
18
+ connection;
19
+ constructor(config, connection) {
20
+ this.config = config;
21
+ this.connection = connection;
22
+ }
23
+ async initialize() {
24
+ const { collectionNamePrefix } = this.config;
25
+ const runsCollection = `${collectionNamePrefix}_test_runs`;
26
+ const testsCollection = `${collectionNamePrefix}_tests`;
27
+ const testsInfoCollection = `${collectionNamePrefix}_tests_info`;
28
+ const database = this.connection.db;
29
+ const collections = await database.collections();
30
+ const set = new Set(collections.map((c) => c.collectionName));
31
+ await Promise.all([
32
+ !set.has(runsCollection) ? database.createCollection(runsCollection) : Promise.resolve(),
33
+ !set.has(testsCollection) ? database.createCollection(testsCollection)
34
+ .then(c => c.createIndex({ status: 1 })) : Promise.resolve(),
35
+ !set.has(testsInfoCollection) ? database.createCollection(testsInfoCollection) : Promise.resolve(),
36
+ ]);
37
+ }
38
+ };
39
+ MongoInitializer = __decorate([
40
+ injectable(),
41
+ __param(0, inject(MONGO_CONFIG)),
42
+ __param(1, inject(MONGO_CONNECTION)),
43
+ __metadata("design:paramtypes", [Object, MongoConnection])
44
+ ], MongoInitializer);
45
+ export { MongoInitializer };
@@ -0,0 +1,18 @@
1
+ import type { ShardHandler } from '@playwright-orchestrator/core';
2
+ import type { TestItem, TestRunConfig } from '@playwright-orchestrator/core';
3
+ import type { CreateArgs } from './create-args.js';
4
+ import { MongoConnection } from './mongo-connection.js';
5
+ export declare class MongoShardHandler implements ShardHandler {
6
+ private readonly runsCollection;
7
+ private readonly testsCollection;
8
+ private readonly connection;
9
+ constructor({ collectionNamePrefix }: CreateArgs, connection: MongoConnection);
10
+ getNextTest(runId: string, _config: TestRunConfig): Promise<TestItem | undefined>;
11
+ getNextTestByProject(runId: string, project: string): Promise<TestItem | undefined>;
12
+ private claimNextTest;
13
+ startShard(runId: string): Promise<TestRunConfig>;
14
+ finishShard(runId: string): Promise<void>;
15
+ private get runs();
16
+ private get tests();
17
+ private generateTestIdQuery;
18
+ }
@@ -0,0 +1,98 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __metadata = (this && this.__metadata) || function (k, v) {
8
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
9
+ };
10
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
11
+ return function (target, key) { decorator(target, key, paramIndex); }
12
+ };
13
+ import { injectable, inject } from 'inversify';
14
+ import { RunStatus, TestStatus } from '@playwright-orchestrator/core';
15
+ import { MongoConnection } from './mongo-connection.js';
16
+ import { MONGO_CONFIG, MONGO_CONNECTION } from './symbols.js';
17
+ import { generateTestId, generateRunId, parseTestId } from './helpers.js';
18
+ const MAX_ORDER = 0b1111111111111111;
19
+ let MongoShardHandler = class MongoShardHandler {
20
+ runsCollection;
21
+ testsCollection;
22
+ connection;
23
+ constructor({ collectionNamePrefix }, connection) {
24
+ this.connection = connection;
25
+ this.runsCollection = `${collectionNamePrefix}_test_runs`;
26
+ this.testsCollection = `${collectionNamePrefix}_tests`;
27
+ }
28
+ async getNextTest(runId, _config) {
29
+ return this.claimNextTest(runId);
30
+ }
31
+ async getNextTestByProject(runId, project) {
32
+ return this.claimNextTest(runId, project);
33
+ }
34
+ async claimNextTest(runId, project) {
35
+ const query = project
36
+ ? { ...this.generateTestIdQuery(runId, TestStatus.Ready), projects: project }
37
+ : this.generateTestIdQuery(runId, TestStatus.Ready);
38
+ const result = await this.tests.findOneAndUpdate(query, {
39
+ $set: { updated: new Date(), status: TestStatus.Ongoing },
40
+ });
41
+ if (!result)
42
+ return undefined;
43
+ const { file, line, column, projects, timeout, ema, children, testId } = result;
44
+ const { order } = parseTestId(result._id);
45
+ return { file, position: `${line}:${column}`, projects, timeout, ema, order, children, testId };
46
+ }
47
+ async startShard(runId) {
48
+ const now = new Date();
49
+ const run = await this.runs.findOneAndUpdate({ _id: generateRunId(runId) }, [
50
+ {
51
+ $set: {
52
+ status: {
53
+ $cond: {
54
+ if: { $in: ['$status', [RunStatus.Created, RunStatus.Run]] },
55
+ then: RunStatus.Run,
56
+ else: RunStatus.RepeatRun,
57
+ },
58
+ },
59
+ updated: now,
60
+ },
61
+ },
62
+ ]);
63
+ if (!run)
64
+ throw new Error(`Run ${runId} not found`);
65
+ const { status: statusBefore } = run;
66
+ if (statusBefore === RunStatus.Created || statusBefore === RunStatus.Finished) {
67
+ await this.tests.updateMany(this.generateTestIdQuery(runId, TestStatus.Failed), {
68
+ $set: { status: TestStatus.Ready, updated: now },
69
+ });
70
+ }
71
+ return run.config;
72
+ }
73
+ async finishShard(runId) {
74
+ await this.runs.updateOne({ _id: generateRunId(runId) }, { $set: { status: RunStatus.Finished, updated: new Date() } });
75
+ }
76
+ get runs() {
77
+ return this.connection.db.collection(this.runsCollection);
78
+ }
79
+ get tests() {
80
+ return this.connection.db.collection(this.testsCollection);
81
+ }
82
+ generateTestIdQuery(runId, ...statuses) {
83
+ return {
84
+ _id: {
85
+ $gte: generateTestId(runId, 0),
86
+ $lt: generateTestId(runId, MAX_ORDER),
87
+ },
88
+ status: { $in: statuses },
89
+ };
90
+ }
91
+ };
92
+ MongoShardHandler = __decorate([
93
+ injectable(),
94
+ __param(0, inject(MONGO_CONFIG)),
95
+ __param(1, inject(MONGO_CONNECTION)),
96
+ __metadata("design:paramtypes", [Object, MongoConnection])
97
+ ], MongoShardHandler);
98
+ export { MongoShardHandler };
@@ -0,0 +1,14 @@
1
+ import { BaseTestRunCreator } from '@playwright-orchestrator/core';
2
+ import type { TestItem, TestRun, TestSortItem } from '@playwright-orchestrator/core';
3
+ import type { CreateArgs } from './create-args.js';
4
+ import { MongoConnection } from './mongo-connection.js';
5
+ export declare class MongoTestRunCreator extends BaseTestRunCreator {
6
+ private readonly runsCollection;
7
+ private readonly testsCollection;
8
+ private readonly testsInfoCollection;
9
+ private readonly debug;
10
+ private readonly connection;
11
+ constructor(args: CreateArgs, connection: MongoConnection);
12
+ loadTestInfos(tests: TestItem[]): Promise<Map<string, TestSortItem>>;
13
+ saveRunData(runId: string, testRun: TestRun, tests: TestItem[]): Promise<void>;
14
+ }
@@ -0,0 +1,89 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __metadata = (this && this.__metadata) || function (k, v) {
8
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
9
+ };
10
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
11
+ return function (target, key) { decorator(target, key, paramIndex); }
12
+ };
13
+ import { injectable, inject, injectFromBase } from 'inversify';
14
+ import { BaseTestRunCreator, TestStatus } from '@playwright-orchestrator/core';
15
+ import { MongoConnection } from './mongo-connection.js';
16
+ import { MONGO_CONFIG, MONGO_CONNECTION } from './symbols.js';
17
+ import { generateRunId, generateTestId } from './helpers.js';
18
+ let MongoTestRunCreator = class MongoTestRunCreator extends BaseTestRunCreator {
19
+ runsCollection;
20
+ testsCollection;
21
+ testsInfoCollection;
22
+ debug;
23
+ connection;
24
+ constructor(args, connection) {
25
+ super();
26
+ this.connection = connection;
27
+ this.runsCollection = `${args.collectionNamePrefix}_test_runs`;
28
+ this.testsCollection = `${args.collectionNamePrefix}_tests`;
29
+ this.testsInfoCollection = `${args.collectionNamePrefix}_tests_info`;
30
+ this.debug = args.debug ?? false;
31
+ }
32
+ async loadTestInfos(tests) {
33
+ const testInfo = this.connection.db.collection(this.testsInfoCollection);
34
+ const testInfoMap = new Map();
35
+ for (const { testId } of tests) {
36
+ if (!testInfoMap.has(testId)) {
37
+ const item = await testInfo.findOneAndUpdate({ _id: testId }, {
38
+ $setOnInsert: {
39
+ _id: testId,
40
+ create: new Date(),
41
+ ema: 0,
42
+ history: [],
43
+ },
44
+ }, { upsert: true, returnDocument: 'after' });
45
+ testInfoMap.set(testId, {
46
+ ema: item.ema,
47
+ fails: item.history.filter((h) => h.status === TestStatus.Failed).length,
48
+ });
49
+ }
50
+ }
51
+ return testInfoMap;
52
+ }
53
+ async saveRunData(runId, testRun, tests) {
54
+ const now = new Date();
55
+ const run = {
56
+ _id: generateRunId(runId),
57
+ ...testRun,
58
+ updated: now,
59
+ };
60
+ await this.connection.db.collection(this.runsCollection).insertOne(run);
61
+ if (tests.length === 0)
62
+ return;
63
+ await this.connection.db.collection(this.testsCollection).insertMany(tests.map(({ file, order, position, projects, timeout, ema, children, testId }) => {
64
+ const [line, column] = position.split(':').map(Number);
65
+ return {
66
+ _id: generateTestId(runId, order),
67
+ testId,
68
+ file,
69
+ projects,
70
+ timeout,
71
+ ema,
72
+ line,
73
+ column,
74
+ status: TestStatus.Ready,
75
+ updated: now,
76
+ children,
77
+ ...(this.debug ? { runId, order } : {}),
78
+ };
79
+ }));
80
+ }
81
+ };
82
+ MongoTestRunCreator = __decorate([
83
+ injectable(),
84
+ injectFromBase({ extendProperties: true, extendConstructorArguments: false }),
85
+ __param(0, inject(MONGO_CONFIG)),
86
+ __param(1, inject(MONGO_CONNECTION)),
87
+ __metadata("design:paramtypes", [Object, MongoConnection])
88
+ ], MongoTestRunCreator);
89
+ export { MongoTestRunCreator };
@@ -0,0 +1,2 @@
1
+ export declare const MONGO_CONFIG: unique symbol;
2
+ export declare const MONGO_CONNECTION: unique symbol;
@@ -0,0 +1,2 @@
1
+ export const MONGO_CONFIG = Symbol.for('MongoConfig');
2
+ export const MONGO_CONNECTION = Symbol.for('MongoConnection');
package/dist/types.d.ts CHANGED
@@ -1,12 +1,10 @@
1
- import { RunStatus, TestConfig, TestItem, TestStatus } from '@playwright-orchestrator/core';
1
+ import { RunStatus, TestItem, TestRunConfig, TestStatus } from '@playwright-orchestrator/core';
2
2
  import { Binary, Document } from 'mongodb';
3
3
  export interface TestRunDocument extends Document {
4
4
  _id: Binary;
5
5
  status: RunStatus;
6
- config: TestConfig;
7
- args: string[];
6
+ config: TestRunConfig;
8
7
  updated: Date;
9
- historyWindow: number;
10
8
  }
11
9
  export interface TestDocument extends Document, Omit<TestItem, 'order' | 'position'> {
12
10
  _id: Binary;
package/package.json CHANGED
@@ -1,32 +1,32 @@
1
1
  {
2
- "name": "@playwright-orchestrator/mongo",
3
- "version": "1.2.0",
4
- "keywords": [],
5
- "author": "Rostyslav Kudrevatykh",
6
- "license": "Apache-2.0",
7
- "description": "Playwright orchestrator MongoDB plugin",
8
- "repository": {
9
- "type": "git",
10
- "url": "git+https://github.com/rostmanrk/playwright-orchestrator.git"
11
- },
12
- "files": [
13
- "dist"
14
- ],
15
- "dependencies": {
16
- "@commander-js/extra-typings": "^13.0.0",
17
- "@playwright-orchestrator/core": "^1.1.0",
18
- "commander": "^13.0.0",
19
- "mongodb": "^6.12.0"
20
- },
21
- "devDependencies": {},
22
- "main": "dist/index.js",
23
- "type": "module",
24
- "exports": {
25
- ".": {
26
- "default": "./dist/index.js"
27
- }
28
- },
29
- "scripts": {
30
- "prepare": "cp ../../LICENSE.md ./"
2
+ "name": "@playwright-orchestrator/mongo",
3
+ "version": "1.3.0",
4
+ "keywords": [],
5
+ "author": "Rostyslav Kudrevatykh",
6
+ "license": "Apache-2.0",
7
+ "description": "Playwright orchestrator MongoDB plugin",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/rostmanrk/playwright-orchestrator.git"
11
+ },
12
+ "files": [
13
+ "dist"
14
+ ],
15
+ "dependencies": {
16
+ "@commander-js/extra-typings": "^13.0.0",
17
+ "commander": "^13.0.0",
18
+ "inversify": "^8.0.0-beta.0",
19
+ "mongodb": "^6.12.0",
20
+ "uuid": "^11.0.0",
21
+ "@playwright-orchestrator/core": "1.3.0"
22
+ },
23
+ "devDependencies": {},
24
+ "main": "dist/index.js",
25
+ "type": "module",
26
+ "exports": {
27
+ ".": {
28
+ "default": "./dist/index.js"
31
29
  }
32
- }
30
+ },
31
+ "scripts": {}
32
+ }