@toa.io/storages.mongodb 1.0.0-alpha.7 → 1.0.0-alpha.8

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@toa.io/storages.mongodb",
3
- "version": "1.0.0-alpha.7",
3
+ "version": "1.0.0-alpha.8",
4
4
  "description": "Toa MongoDB Storage Connector",
5
5
  "author": "temich <tema.gurtovoy@gmail.com>",
6
6
  "homepage": "https://github.com/toa-io/toa#readme",
@@ -19,13 +19,13 @@
19
19
  "test": "echo \"Error: run tests from root\" && exit 1"
20
20
  },
21
21
  "dependencies": {
22
- "@toa.io/console": "1.0.0-alpha.7",
23
- "@toa.io/conveyor": "1.0.0-alpha.7",
24
- "@toa.io/core": "1.0.0-alpha.7",
25
- "@toa.io/generic": "1.0.0-alpha.7",
26
- "@toa.io/pointer": "1.0.0-alpha.7",
22
+ "@toa.io/console": "1.0.0-alpha.8",
23
+ "@toa.io/conveyor": "1.0.0-alpha.8",
24
+ "@toa.io/core": "1.0.0-alpha.8",
25
+ "@toa.io/generic": "1.0.0-alpha.8",
26
+ "@toa.io/pointer": "1.0.0-alpha.8",
27
27
  "mongodb": "6.3.0",
28
28
  "saslprep": "1.0.3"
29
29
  },
30
- "gitHead": "4f5ac0bc342d4b7bd469fbe5c74266f050b55c9f"
30
+ "gitHead": "2ee18835c8214600e1d354251fa632913bff38c3"
31
31
  }
package/src/client.js ADDED
@@ -0,0 +1,131 @@
1
+ 'use strict'
2
+
3
+ /**
4
+ * @typedef {import('mongodb').MongoClient} MongoClient
5
+ * @typedef {{ count: number, client: MongoClient }} Instance
6
+ * @typedef {import('@toa.io/core').Locator} Locator
7
+ */
8
+
9
+ const { Connector } = require('@toa.io/core')
10
+ const { resolve } = require('@toa.io/pointer')
11
+ const { ID } = require('./deployment')
12
+ const { MongoClient } = require('mongodb')
13
+
14
+ /**
15
+ * @type {Record<string, Promise<Instance>>}
16
+ */
17
+ const INSTANCES = {}
18
+
19
+ class Client extends Connector {
20
+ /**
21
+ * @public
22
+ * @type {import('mongodb').Collection}
23
+ */
24
+ collection
25
+
26
+ /**
27
+ * @private
28
+ * @type {Locator}
29
+ */
30
+ locator
31
+
32
+ /**
33
+ * @private
34
+ * @type {Instance}
35
+ */
36
+ instance
37
+
38
+ /**
39
+ * @private
40
+ * @type {string}
41
+ */
42
+ key
43
+
44
+ /**
45
+ * @param {Locator} locator
46
+ */
47
+ constructor (locator) {
48
+ super()
49
+
50
+ this.locator = locator
51
+ }
52
+
53
+ /**
54
+ * @protected
55
+ * @override
56
+ * @return {Promise<void>}
57
+ */
58
+ async open () {
59
+ const urls = await this.resolveURLs()
60
+
61
+ this.key = getKey(urls)
62
+
63
+ INSTANCES[this.key] ??= this.createInstance(urls)
64
+
65
+ this.instance = await INSTANCES[this.key]
66
+ this.instance.count++
67
+
68
+ this.collection = this.instance.client
69
+ .db(this.locator.namespace)
70
+ .collection(this.locator.name)
71
+ }
72
+
73
+ /**
74
+ * @protected
75
+ * @override
76
+ * @return {Promise<void>}
77
+ */
78
+ async close () {
79
+ const instance = await INSTANCES[this.key]
80
+
81
+ instance.count--
82
+
83
+ if (instance.count === 0) {
84
+ await instance.client.close()
85
+ delete INSTANCES[this.key]
86
+ }
87
+ }
88
+
89
+ /**
90
+ * @private
91
+ * @param {string[]} urls
92
+ * @return {Promise<Instance>}
93
+ */
94
+ async createInstance (urls) {
95
+ const client = new MongoClient(urls.join(','), OPTIONS)
96
+ const hosts = urls.map((str) => new URL(str).host)
97
+
98
+ console.info('Connecting to MongoDB:', hosts.join(', '))
99
+
100
+ await client.connect()
101
+
102
+ return {
103
+ count: 0,
104
+ client
105
+ }
106
+ }
107
+
108
+ /**
109
+ * @private
110
+ * @return {Promise<string[]>}
111
+ */
112
+ async resolveURLs () {
113
+ if (process.env.TOA_DEV === '1') {
114
+ return ['mongodb://developer:secret@localhost']
115
+ } else {
116
+ return await resolve(ID, this.locator.id)
117
+ }
118
+ }
119
+ }
120
+
121
+ function getKey (urls) {
122
+ return urls.sort().join(' ')
123
+ }
124
+
125
+ const OPTIONS = {
126
+ ignoreUndefined: true,
127
+ connectTimeoutMS: 0,
128
+ serverSelectionTimeoutMS: 0
129
+ }
130
+
131
+ exports.Client = Client
@@ -0,0 +1,69 @@
1
+ 'use strict'
2
+
3
+ const { Connector } = require('@toa.io/core')
4
+
5
+ class Collection extends Connector {
6
+ #client
7
+ #collection
8
+
9
+ constructor (client) {
10
+ super()
11
+
12
+ this.#client = client
13
+
14
+ this.depends(client)
15
+ }
16
+
17
+ async open () {
18
+ this.#collection = this.#client.collection
19
+ }
20
+
21
+ /** @hot */
22
+ async get (query, options) {
23
+ return /** @type {toa.mongodb.Record} */ this.#collection.findOne(query, options)
24
+ }
25
+
26
+ /** @hot */
27
+ async find (query, options) {
28
+ const cursor = this.#collection.find(query, options)
29
+
30
+ return cursor.toArray()
31
+ }
32
+
33
+ /** @hot */
34
+ async add (record) {
35
+ return await this.#collection.insertOne(record)
36
+ }
37
+
38
+ /** @hot */
39
+ async replace (query, record, options) {
40
+ return await this.#collection.findOneAndReplace(query, record, options)
41
+ }
42
+
43
+ /** @hot */
44
+ async update (query, update, options) {
45
+ return this.#collection.findOneAndUpdate(query, update, options)
46
+ }
47
+
48
+ async index (keys, options) {
49
+ return this.#collection.createIndex(keys, options)
50
+ }
51
+
52
+ async indexes () {
53
+ try {
54
+ const array = await this.#collection.listIndexes().toArray()
55
+
56
+ return array.map(({ name }) => name).filter((name) => name !== '_id_')
57
+ } catch {
58
+ return []
59
+ }
60
+ }
61
+
62
+ async dropIndexes (names) {
63
+ const all = names.map((name) => this.#collection.dropIndex(name))
64
+
65
+ return Promise.all(all)
66
+ }
67
+ }
68
+
69
+ exports.Collection = Collection
package/src/factory.js CHANGED
@@ -1,13 +1,15 @@
1
1
  'use strict'
2
2
 
3
- const { Connection } = require('./connection')
3
+ const { Client } = require('./client')
4
+ const { Collection } = require('./collection')
4
5
  const { Storage } = require('./storage')
5
6
 
6
7
  class Factory {
7
- storage (locator) {
8
- const connection = new Connection(locator)
8
+ storage (locator, entity) {
9
+ const client = new Client(locator)
10
+ const connection = new Collection(client)
9
11
 
10
- return new Storage(connection)
12
+ return new Storage(connection, entity)
11
13
  }
12
14
  }
13
15
 
package/src/storage.js CHANGED
@@ -1,6 +1,9 @@
1
1
  'use strict'
2
2
 
3
- const { Connector } = require('@toa.io/core')
3
+ const {
4
+ Connector,
5
+ exceptions
6
+ } = require('@toa.io/core')
4
7
 
5
8
  const { translate } = require('./translate')
6
9
  const {
@@ -8,24 +11,23 @@ const {
8
11
  from
9
12
  } = require('./record')
10
13
 
11
- /**
12
- * @implements {toa.core.Storage}
13
- */
14
14
  class Storage extends Connector {
15
- /** @type {toa.mongodb.Connection} */
16
15
  #connection
16
+ #entity
17
17
 
18
- /**
19
- * @param {toa.mongodb.Connection} connection
20
- */
21
- constructor (connection) {
18
+ constructor (connection, entity) {
22
19
  super()
23
20
 
24
21
  this.#connection = connection
22
+ this.#entity = entity
25
23
 
26
24
  this.depends(connection)
27
25
  }
28
26
 
27
+ async open () {
28
+ await this.index()
29
+ }
30
+
29
31
  async get (query) {
30
32
  const {
31
33
  criteria,
@@ -49,8 +51,9 @@ class Storage extends Connector {
49
51
 
50
52
  async add (entity) {
51
53
  const record = to(entity)
54
+ const result = await this.#connection.add(record)
52
55
 
53
- return await this.#connection.add(record)
56
+ return result.acknowledged
54
57
  }
55
58
 
56
59
  async set (entity) {
@@ -64,10 +67,18 @@ class Storage extends Connector {
64
67
  }
65
68
 
66
69
  async store (entity) {
67
- if (entity._version === 1) {
68
- return this.add(entity)
69
- } else {
70
- return this.set(entity)
70
+ try {
71
+ if (entity._version === 1) {
72
+ return await this.add(entity)
73
+ } else {
74
+ return await this.set(entity)
75
+ }
76
+ } catch (error) {
77
+ if (error.code === ERR_DUPLICATE_KEY) {
78
+ return new exceptions.DuplicateException(Object.keys(error.keyValue))
79
+ } else {
80
+ throw error
81
+ }
71
82
  }
72
83
  }
73
84
 
@@ -102,6 +113,97 @@ class Storage extends Connector {
102
113
 
103
114
  return from(result)
104
115
  }
116
+
117
+ async index () {
118
+ const indexes = []
119
+
120
+ if (this.#entity.unique !== undefined) {
121
+ for (const [name, fields] of Object.entries(this.#entity.unique)) {
122
+ const sparse = this.checkFields(fields)
123
+ const unique = await this.uniqueIndex(name, fields, sparse)
124
+
125
+ indexes.push(unique)
126
+ }
127
+ }
128
+
129
+ if (this.#entity.index !== undefined) {
130
+ for (const [suffix, declaration] of Object.entries(this.#entity.index)) {
131
+ const name = 'index_' + suffix
132
+ const fields = Object.fromEntries(Object.entries(declaration)
133
+ .map(([name, type]) => [name, INDEX_TYPES[type]]))
134
+
135
+ const sparse = this.checkFields(Object.keys(fields))
136
+
137
+ await this.#connection.index(fields, {
138
+ name,
139
+ sparse
140
+ })
141
+
142
+ indexes.push(name)
143
+ }
144
+ }
145
+
146
+ await this.removeObsolete(indexes)
147
+ }
148
+
149
+ async uniqueIndex (name, properties, sparse = false) {
150
+ const fields = properties.reduce((acc, property) => {
151
+ acc[property] = 1
152
+ return acc
153
+ }, {})
154
+
155
+ name = 'unique_' + name
156
+
157
+ await this.#connection.index(fields, {
158
+ name,
159
+ unique: true,
160
+ sparse
161
+ })
162
+
163
+ return name
164
+ }
165
+
166
+ async removeObsolete (desired) {
167
+ const current = await this.#connection.indexes()
168
+ const obsolete = current.filter((name) => !desired.includes(name))
169
+
170
+ if (obsolete.length > 0) {
171
+ console.info(`Remove obsolete indexes: [${obsolete.join(', ')}]`)
172
+
173
+ await this.#connection.dropIndexes(obsolete)
174
+ }
175
+ }
176
+
177
+ checkFields (fields) {
178
+ const optional = []
179
+
180
+ for (const field of fields) {
181
+ if (!(field in this.#entity.schema.properties)) {
182
+ throw new Error(`Index field '${field}' is not defined.`)
183
+ }
184
+
185
+ if (!this.#entity.schema.required?.includes(field)) {
186
+ optional.push(field)
187
+ }
188
+ }
189
+
190
+ if (optional.length > 0) {
191
+ console.info(`Index fields [${optional.join(', ')}] are optional, creating sparse index.`)
192
+
193
+ return true
194
+ } else {
195
+ return false
196
+ }
197
+ }
198
+
105
199
  }
106
200
 
201
+ const INDEX_TYPES = {
202
+ 'asc': 1,
203
+ 'desc': -1,
204
+ 'hash': 'hashed'
205
+ }
206
+
207
+ const ERR_DUPLICATE_KEY = 11000
208
+
107
209
  exports.Storage = Storage
package/src/connection.js DELETED
@@ -1,103 +0,0 @@
1
- // noinspection JSCheckFunctionSignatures
2
-
3
- 'use strict'
4
-
5
- const { MongoClient } = require('mongodb')
6
- const { Connector } = require('@toa.io/core')
7
- const { resolve } = require('@toa.io/pointer')
8
- const { Conveyor } = require('@toa.io/conveyor')
9
- const { ID } = require('./deployment')
10
-
11
- class Connection extends Connector {
12
- #locator
13
- /** @type {import('mongodb').MongoClient} */
14
- #client
15
- /** @type {import('mongodb').Collection<toa.mongodb.Record>} */
16
- #collection
17
- /** @type {toa.conveyor.Conveyor<toa.core.storages.Record, boolean>} */
18
- #conveyor
19
-
20
- constructor (locator) {
21
- super()
22
-
23
- this.#locator = locator
24
- }
25
-
26
- async open () {
27
- const urls = await this.#resolveURLs()
28
- const db = this.#locator.namespace
29
- const collection = this.#locator.name
30
-
31
- this.#client = new MongoClient(urls[0], OPTIONS)
32
-
33
- await this.#client.connect()
34
-
35
- this.#collection = this.#client.db(db).collection(collection)
36
- this.#conveyor = new Conveyor((objects) => this.addMany(objects))
37
-
38
- console.info(`Storage Mongo '${this.#locator.id}' connected`)
39
- }
40
-
41
- async close () {
42
- await this.#client?.close()
43
-
44
- console.info(`Storage Mongo '${this.#locator.id}' disconnected`)
45
- }
46
-
47
- /** @hot */
48
- async get (query, options) {
49
- return /** @type {toa.mongodb.Record} */ this.#collection.findOne(query, options)
50
- }
51
-
52
- /** @hot */
53
- async find (query, options) {
54
- const cursor = this.#collection.find(query, options)
55
-
56
- return cursor.toArray()
57
- }
58
-
59
- /** @hot */
60
- async add (record) {
61
- return this.#conveyor.process(record)
62
- }
63
-
64
- async addMany (records) {
65
- let result
66
-
67
- try {
68
- const response = await this.#collection.insertMany(records, { ordered: false })
69
-
70
- result = response.acknowledged
71
- } catch (e) {
72
- if (e.code === ERR_DUPLICATE_KEY) result = false
73
- else throw e
74
- }
75
-
76
- return result
77
- }
78
-
79
- /** @hot */
80
- async replace (query, record, options) {
81
- return await this.#collection.findOneAndReplace(query, record, options)
82
- }
83
-
84
- /** @hot */
85
- async update (query, update, options) {
86
- return this.#collection.findOneAndUpdate(query, update, options)
87
- }
88
-
89
- async #resolveURLs () {
90
- if (process.env.TOA_DEV === '1') return ['mongodb://developer:secret@localhost']
91
- else return await resolve(ID, this.#locator.id)
92
- }
93
- }
94
-
95
- const OPTIONS = {
96
- ignoreUndefined: true,
97
- connectTimeoutMS: 0,
98
- serverSelectionTimeoutMS: 0
99
- }
100
-
101
- const ERR_DUPLICATE_KEY = 11000
102
-
103
- exports.Connection = Connection
@@ -1,58 +0,0 @@
1
- 'use strict'
2
-
3
- const insertManyMock = jest.fn(() => ({ acknowledged: true }))
4
- jest.mock('mongodb', () => ({
5
- __esModule: true,
6
- MongoClient: function () {
7
- this.connect = () => {},
8
- this.db = () => ({
9
- collection: () => ({
10
- insertMany: insertManyMock
11
- })
12
- })
13
- return this
14
- },
15
- }))
16
- jest.mock('@toa.io/pointer', () => ({
17
- __esModule: true,
18
- resolve: () => ['url'],
19
- }))
20
- const { generate } = require('randomstring')
21
- const { Connection } = require('../src/connection')
22
-
23
-
24
- let connection
25
-
26
- beforeEach(async () => {
27
- jest.clearAllMocks()
28
- connection = new Connection({ id: 1 })
29
- await connection.open()
30
- })
31
-
32
- it('should be', () => {
33
- expect(Connection).toBeDefined()
34
- })
35
-
36
- it('should insert', async () => {
37
- const object = generate()
38
-
39
- await connection.add(object)
40
-
41
- expect(insertManyMock).toHaveBeenCalledWith([object], { ordered: false })
42
- })
43
-
44
- it('should batch insert', async () => {
45
- const a = generate()
46
- const b = generate()
47
- const c = generate()
48
-
49
- await Promise.all([
50
- connection.add(a),
51
- connection.add(b),
52
- connection.add(c)
53
- ])
54
-
55
- expect(insertManyMock).toHaveBeenCalledTimes(2)
56
- expect(insertManyMock).toHaveBeenNthCalledWith(1, [a], { ordered: false })
57
- expect(insertManyMock).toHaveBeenNthCalledWith(2, [b, c], { ordered: false })
58
- })