fib-orm 1.4.2 → 2.0.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.
Files changed (295) hide show
  1. package/License +1 -1
  2. package/README.md +53 -0
  3. package/lib/cli/commands/ddlFrom.d.ts +2 -0
  4. package/lib/cli/commands/ddlFrom.js +74 -0
  5. package/lib/cli/commands/dumpModel.d.ts +2 -0
  6. package/lib/cli/commands/dumpModel.js +106 -0
  7. package/lib/cli/commands/escape.d.ts +2 -0
  8. package/lib/cli/commands/escape.js +68 -0
  9. package/lib/cli/commands/spinner.d.ts +2 -0
  10. package/lib/cli/commands/spinner.js +36 -0
  11. package/lib/cli/commands/upgrade.d.ts +2 -0
  12. package/lib/cli/commands/upgrade.js +65 -0
  13. package/lib/cli/helpers/ddl.d.ts +17 -0
  14. package/lib/cli/helpers/ddl.js +55 -0
  15. package/lib/cli/helpers/package.d.ts +26 -0
  16. package/lib/cli/helpers/package.js +56 -0
  17. package/lib/cli/index.d.ts +2 -0
  18. package/lib/cli/index.js +18 -0
  19. package/lib/codepoints-map.json +762 -0
  20. package/lib/db-driver/Typo.d.ts +112 -0
  21. package/lib/db-driver/Typo.js +1 -0
  22. package/lib/db-driver/built-ins/base.class.d.ts +96 -0
  23. package/lib/db-driver/built-ins/base.class.js +186 -0
  24. package/lib/db-driver/built-ins/driver-dm.d.ts +18 -0
  25. package/lib/db-driver/built-ins/driver-dm.js +53 -0
  26. package/lib/db-driver/built-ins/driver-mongodb.d.ts +24 -0
  27. package/lib/db-driver/built-ins/driver-mongodb.js +46 -0
  28. package/lib/db-driver/built-ins/driver-mysql.d.ts +18 -0
  29. package/lib/db-driver/built-ins/driver-mysql.js +37 -0
  30. package/lib/db-driver/built-ins/driver-postgresql.d.ts +22 -0
  31. package/lib/db-driver/built-ins/driver-postgresql.js +76 -0
  32. package/lib/db-driver/built-ins/driver-redis.d.ts +12 -0
  33. package/lib/db-driver/built-ins/driver-redis.js +35 -0
  34. package/lib/db-driver/built-ins/driver-sqlite.d.ts +17 -0
  35. package/lib/db-driver/built-ins/driver-sqlite.js +34 -0
  36. package/lib/db-driver/index.d.ts +3 -0
  37. package/lib/db-driver/index.js +4 -0
  38. package/lib/db-driver/utils.d.ts +14 -0
  39. package/lib/db-driver/utils.js +187 -0
  40. package/lib/knex/deps/tarn/dist/PendingOperation.d.ts +12 -0
  41. package/lib/knex/deps/tarn/dist/PendingOperation.js +48 -0
  42. package/lib/knex/deps/tarn/dist/Pool.d.ts +97 -0
  43. package/lib/knex/deps/tarn/dist/Pool.js +516 -0
  44. package/lib/knex/deps/tarn/dist/PromiseInspection.d.ts +16 -0
  45. package/lib/knex/deps/tarn/dist/PromiseInspection.js +21 -0
  46. package/lib/knex/deps/tarn/dist/Resource.d.ts +9 -0
  47. package/lib/knex/deps/tarn/dist/Resource.js +19 -0
  48. package/lib/knex/deps/tarn/dist/TimeoutError.d.ts +2 -0
  49. package/lib/knex/deps/tarn/dist/TimeoutError.js +5 -0
  50. package/lib/knex/deps/tarn/dist/tarn.d.ts +3 -0
  51. package/lib/knex/deps/tarn/dist/tarn.js +10 -0
  52. package/lib/knex/deps/tarn/dist/utils.d.ts +14 -0
  53. package/lib/knex/deps/tarn/dist/utils.js +60 -0
  54. package/lib/knex/knex.d.ts +2 -0
  55. package/lib/knex/knex.js +3 -0
  56. package/lib/knex/sandbox.d.ts +4 -0
  57. package/lib/knex/sandbox.js +22 -0
  58. package/lib/orm/Adapters.d.ts +3 -0
  59. package/lib/orm/Adapters.js +44 -0
  60. package/lib/orm/AggregateFunctions.d.ts +3 -0
  61. package/lib/orm/AggregateFunctions.js +176 -0
  62. package/lib/orm/Associations/Extend.d.ts +22 -0
  63. package/lib/orm/Associations/Extend.js +274 -0
  64. package/lib/orm/Associations/Many.d.ts +17 -0
  65. package/lib/orm/Associations/Many.js +569 -0
  66. package/lib/orm/Associations/One.d.ts +16 -0
  67. package/lib/orm/Associations/One.js +310 -0
  68. package/lib/orm/Associations/_utils.d.ts +15 -0
  69. package/lib/orm/Associations/_utils.js +52 -0
  70. package/lib/orm/ChainFind.d.ts +3 -0
  71. package/lib/orm/ChainFind.js +327 -0
  72. package/lib/orm/ChainInstance.d.ts +6 -0
  73. package/lib/orm/ChainInstance.js +73 -0
  74. package/lib/orm/Debug.d.ts +2 -0
  75. package/lib/orm/Debug.js +17 -0
  76. package/lib/orm/Drivers/DB/base.d.ts +3 -0
  77. package/lib/orm/Drivers/DB/base.js +3 -0
  78. package/lib/orm/Drivers/DB/dm.d.ts +11 -0
  79. package/lib/orm/Drivers/DB/dm.js +23 -0
  80. package/lib/orm/Drivers/DB/mysql.d.ts +11 -0
  81. package/lib/orm/Drivers/DB/mysql.js +23 -0
  82. package/lib/orm/Drivers/DB/postgres.d.ts +11 -0
  83. package/lib/orm/Drivers/DB/postgres.js +22 -0
  84. package/lib/orm/Drivers/DB/sqlite3.d.ts +16 -0
  85. package/lib/orm/Drivers/DB/sqlite3.js +39 -0
  86. package/lib/orm/Drivers/DML/_ddl-sql.d.ts +3 -0
  87. package/lib/orm/Drivers/DML/_ddl-sql.js +51 -0
  88. package/lib/orm/Drivers/DML/_dml-helpers.d.ts +19 -0
  89. package/lib/orm/Drivers/DML/_dml-helpers.js +51 -0
  90. package/lib/orm/Drivers/DML/_shared.d.ts +9 -0
  91. package/lib/orm/Drivers/DML/_shared.js +38 -0
  92. package/lib/orm/Drivers/DML/_utils.d.ts +8 -0
  93. package/lib/orm/Drivers/DML/_utils.js +67 -0
  94. package/lib/orm/Drivers/DML/constants.d.ts +3 -0
  95. package/lib/orm/Drivers/DML/constants.js +2 -0
  96. package/lib/orm/Drivers/DML/dm.d.ts +2 -0
  97. package/lib/orm/Drivers/DML/dm.js +293 -0
  98. package/lib/orm/Drivers/DML/index.d.ts +4 -0
  99. package/lib/orm/Drivers/DML/index.js +6 -0
  100. package/lib/orm/Drivers/DML/mysql.d.ts +2 -0
  101. package/lib/orm/Drivers/DML/mysql.js +251 -0
  102. package/lib/orm/Drivers/DML/postgres.d.ts +3 -0
  103. package/lib/orm/Drivers/DML/postgres.js +276 -0
  104. package/lib/orm/Drivers/DML/sqlite.d.ts +2 -0
  105. package/lib/orm/Drivers/DML/sqlite.js +266 -0
  106. package/lib/orm/Error.d.ts +11 -0
  107. package/lib/orm/Error.js +40 -0
  108. package/lib/orm/Helpers.d.ts +35 -0
  109. package/lib/orm/Helpers.js +233 -0
  110. package/lib/orm/Hook.d.ts +13 -0
  111. package/lib/orm/Hook.js +99 -0
  112. package/lib/orm/Instance.d.ts +2 -0
  113. package/lib/orm/Instance.js +697 -0
  114. package/lib/orm/LazyLoad.d.ts +4 -0
  115. package/lib/orm/LazyLoad.js +76 -0
  116. package/lib/orm/Model.d.ts +7 -0
  117. package/lib/orm/Model.js +971 -0
  118. package/lib/orm/ORM.d.ts +37 -0
  119. package/lib/orm/ORM.js +241 -0
  120. package/lib/orm/Patch/fib-cache.d.ts +40 -0
  121. package/lib/orm/Patch/fib-cache.js +2 -0
  122. package/lib/orm/Patch/plugin.d.ts +4 -0
  123. package/lib/orm/Patch/plugin.js +13 -0
  124. package/lib/orm/Property.d.ts +9 -0
  125. package/lib/orm/Property.js +71 -0
  126. package/lib/orm/Settings.d.ts +42 -0
  127. package/lib/orm/Settings.js +119 -0
  128. package/lib/orm/Singleton.d.ts +5 -0
  129. package/lib/orm/Singleton.js +72 -0
  130. package/lib/orm/Typo/Adapter.d.ts +5 -0
  131. package/lib/orm/Typo/Adapter.js +1 -0
  132. package/lib/orm/Typo/DMLDriver.d.ts +210 -0
  133. package/lib/orm/Typo/DMLDriver.js +1 -0
  134. package/lib/orm/Typo/Db.d.ts +38 -0
  135. package/lib/orm/Typo/Db.js +1 -0
  136. package/lib/orm/Typo/Error.d.ts +31 -0
  137. package/lib/orm/Typo/Error.js +1 -0
  138. package/lib/orm/Typo/ORM.d.ts +233 -0
  139. package/lib/orm/Typo/ORM.js +3 -0
  140. package/lib/orm/Typo/Validators.d.ts +32 -0
  141. package/lib/orm/Typo/Validators.js +2 -0
  142. package/lib/orm/Typo/_common.d.ts +38 -0
  143. package/lib/orm/Typo/_common.js +1 -0
  144. package/lib/orm/Typo/assoc.d.ts +221 -0
  145. package/lib/orm/Typo/assoc.js +1 -0
  146. package/lib/orm/Typo/hook.d.ts +42 -0
  147. package/lib/orm/Typo/hook.js +1 -0
  148. package/lib/orm/Typo/instance.d.ts +157 -0
  149. package/lib/orm/Typo/instance.js +1 -0
  150. package/lib/orm/Typo/model.d.ts +313 -0
  151. package/lib/orm/Typo/model.js +6 -0
  152. package/lib/orm/Typo/patch.d.ts +31 -0
  153. package/lib/orm/Typo/patch.js +1 -0
  154. package/lib/orm/Typo/property.d.ts +57 -0
  155. package/lib/orm/Typo/property.js +1 -0
  156. package/lib/orm/Typo/query.d.ts +216 -0
  157. package/lib/orm/Typo/query.js +1 -0
  158. package/lib/orm/Typo/settings.d.ts +35 -0
  159. package/lib/orm/Typo/settings.js +5 -0
  160. package/lib/orm/Typo/synchronous.d.ts +47 -0
  161. package/lib/orm/Typo/synchronous.js +1 -0
  162. package/lib/orm/Utilities.d.ts +179 -0
  163. package/lib/orm/Utilities.js +975 -0
  164. package/lib/orm/Validators.d.ts +34 -0
  165. package/lib/orm/Validators.js +100 -0
  166. package/lib/orm/Where/common.d.ts +1 -0
  167. package/lib/orm/Where/common.js +7 -0
  168. package/lib/orm/Where/filterDate.d.ts +11 -0
  169. package/lib/orm/Where/filterDate.js +58 -0
  170. package/lib/orm/index.d.ts +68 -0
  171. package/lib/orm/index.js +157 -0
  172. package/lib/orm-core/callback.d.ts +12 -0
  173. package/lib/orm-core/callback.js +1 -0
  174. package/lib/orm-core/dialect.d.ts +80 -0
  175. package/lib/orm-core/dialect.js +1 -0
  176. package/lib/orm-core/error.d.ts +16 -0
  177. package/lib/orm-core/error.js +29 -0
  178. package/lib/orm-core/index.d.ts +6 -0
  179. package/lib/orm-core/index.js +6 -0
  180. package/lib/orm-core/sync.d.ts +12 -0
  181. package/lib/orm-core/sync.js +1 -0
  182. package/lib/orm-core/utils.d.ts +1 -0
  183. package/lib/orm-core/utils.js +5 -0
  184. package/lib/orm-property/Property.d.ts +78 -0
  185. package/lib/orm-property/Property.js +1 -0
  186. package/lib/orm-property/Utils.d.ts +9 -0
  187. package/lib/orm-property/Utils.js +13 -0
  188. package/lib/orm-property/customTypes.d.ts +2 -0
  189. package/lib/orm-property/customTypes.js +13 -0
  190. package/lib/orm-property/index.d.ts +10 -0
  191. package/lib/orm-property/index.js +22 -0
  192. package/lib/orm-property/transformer.d.ts +5 -0
  193. package/lib/orm-property/transformer.js +10 -0
  194. package/lib/orm-property/transformers/dm.d.ts +29 -0
  195. package/lib/orm-property/transformers/dm.js +237 -0
  196. package/lib/orm-property/transformers/index.d.ts +4 -0
  197. package/lib/orm-property/transformers/index.js +5 -0
  198. package/lib/orm-property/transformers/mysql.d.ts +102 -0
  199. package/lib/orm-property/transformers/mysql.js +261 -0
  200. package/lib/orm-property/transformers/postgresql.d.ts +54 -0
  201. package/lib/orm-property/transformers/postgresql.js +189 -0
  202. package/lib/orm-property/transformers/sqlite.d.ts +19 -0
  203. package/lib/orm-property/transformers/sqlite.js +171 -0
  204. package/lib/sql-ddl-sync/Dialects/dm.d.ts +40 -0
  205. package/lib/sql-ddl-sync/Dialects/dm.js +296 -0
  206. package/lib/sql-ddl-sync/Dialects/index.d.ts +7 -0
  207. package/lib/sql-ddl-sync/Dialects/index.js +7 -0
  208. package/lib/sql-ddl-sync/Dialects/mysql.d.ts +39 -0
  209. package/lib/sql-ddl-sync/Dialects/mysql.js +240 -0
  210. package/lib/sql-ddl-sync/Dialects/postgresql.d.ts +40 -0
  211. package/lib/sql-ddl-sync/Dialects/postgresql.js +286 -0
  212. package/lib/sql-ddl-sync/Dialects/sqlite.d.ts +44 -0
  213. package/lib/sql-ddl-sync/Dialects/sqlite.js +256 -0
  214. package/lib/sql-ddl-sync/SQL.d.ts +12 -0
  215. package/lib/sql-ddl-sync/SQL.js +108 -0
  216. package/lib/sql-ddl-sync/Typo/Collection.d.ts +13 -0
  217. package/lib/sql-ddl-sync/Typo/Collection.js +1 -0
  218. package/lib/sql-ddl-sync/Typo/DbIndex.d.ts +13 -0
  219. package/lib/sql-ddl-sync/Typo/DbIndex.js +1 -0
  220. package/lib/sql-ddl-sync/Typo/Dialect.d.ts +81 -0
  221. package/lib/sql-ddl-sync/Typo/Dialect.js +1 -0
  222. package/lib/sql-ddl-sync/Typo/Driver.d.ts +53 -0
  223. package/lib/sql-ddl-sync/Typo/Driver.js +1 -0
  224. package/lib/sql-ddl-sync/Typo/Query.d.ts +7 -0
  225. package/lib/sql-ddl-sync/Typo/Query.js +1 -0
  226. package/lib/sql-ddl-sync/Typo/SQL.d.ts +31 -0
  227. package/lib/sql-ddl-sync/Typo/SQL.js +1 -0
  228. package/lib/sql-ddl-sync/Typo/_common.d.ts +29 -0
  229. package/lib/sql-ddl-sync/Typo/_common.js +1 -0
  230. package/lib/sql-ddl-sync/Utils.d.ts +40 -0
  231. package/lib/sql-ddl-sync/Utils.js +217 -0
  232. package/lib/sql-ddl-sync/index.d.ts +87 -0
  233. package/lib/sql-ddl-sync/index.js +371 -0
  234. package/lib/sql-query/Comparators.d.ts +3 -0
  235. package/lib/sql-query/Comparators.js +94 -0
  236. package/lib/sql-query/Create.d.ts +35 -0
  237. package/lib/sql-query/Create.js +77 -0
  238. package/lib/sql-query/Dialects/dm.d.ts +3 -0
  239. package/lib/sql-query/Dialects/dm.js +74 -0
  240. package/lib/sql-query/Dialects/index.d.ts +10 -0
  241. package/lib/sql-query/Dialects/index.js +12 -0
  242. package/lib/sql-query/Dialects/mssql.d.ts +3 -0
  243. package/lib/sql-query/Dialects/mssql.js +73 -0
  244. package/lib/sql-query/Dialects/mysql.d.ts +3 -0
  245. package/lib/sql-query/Dialects/mysql.js +100 -0
  246. package/lib/sql-query/Dialects/postgresql.d.ts +3 -0
  247. package/lib/sql-query/Dialects/postgresql.js +76 -0
  248. package/lib/sql-query/Dialects/sqlite.d.ts +3 -0
  249. package/lib/sql-query/Dialects/sqlite.js +61 -0
  250. package/lib/sql-query/Helpers.d.ts +38 -0
  251. package/lib/sql-query/Helpers.js +259 -0
  252. package/lib/sql-query/Insert.d.ts +12 -0
  253. package/lib/sql-query/Insert.js +33 -0
  254. package/lib/sql-query/Query.d.ts +29 -0
  255. package/lib/sql-query/Query.js +119 -0
  256. package/lib/sql-query/Remove.d.ts +16 -0
  257. package/lib/sql-query/Remove.js +93 -0
  258. package/lib/sql-query/Select.d.ts +62 -0
  259. package/lib/sql-query/Select.js +533 -0
  260. package/lib/sql-query/Set.d.ts +4 -0
  261. package/lib/sql-query/Set.js +16 -0
  262. package/lib/sql-query/Typo/Aggregation.d.ts +32 -0
  263. package/lib/sql-query/Typo/Aggregation.js +1 -0
  264. package/lib/sql-query/Typo/Comparators.d.ts +140 -0
  265. package/lib/sql-query/Typo/Comparators.js +1 -0
  266. package/lib/sql-query/Typo/Dialect.d.ts +39 -0
  267. package/lib/sql-query/Typo/Dialect.js +1 -0
  268. package/lib/sql-query/Typo/Field.d.ts +8 -0
  269. package/lib/sql-query/Typo/Field.js +1 -0
  270. package/lib/sql-query/Typo/Helper.d.ts +4 -0
  271. package/lib/sql-query/Typo/Helper.js +1 -0
  272. package/lib/sql-query/Typo/Query-ChainBuilder.d.ts +80 -0
  273. package/lib/sql-query/Typo/Query-ChainBuilder.js +1 -0
  274. package/lib/sql-query/Typo/Query.d.ts +34 -0
  275. package/lib/sql-query/Typo/Query.js +16 -0
  276. package/lib/sql-query/Typo/Sql.d.ts +143 -0
  277. package/lib/sql-query/Typo/Sql.js +1 -0
  278. package/lib/sql-query/Typo/SubQuery.d.ts +39 -0
  279. package/lib/sql-query/Typo/SubQuery.js +1 -0
  280. package/lib/sql-query/Typo/index.d.ts +9 -0
  281. package/lib/sql-query/Typo/index.js +1 -0
  282. package/lib/sql-query/Update.d.ts +15 -0
  283. package/lib/sql-query/Update.js +38 -0
  284. package/lib/sql-query/Where.d.ts +4 -0
  285. package/lib/sql-query/Where.js +280 -0
  286. package/package.json +72 -36
  287. package/.travis.yml +0 -14
  288. package/@types/index.d.ts +0 -254
  289. package/@types/orm_mirror/orm.d.ts +0 -275
  290. package/@types/orm_mirror/sql-query.d.ts +0 -79
  291. package/Readme.md +0 -843
  292. package/lib/index.js +0 -13
  293. package/lib/modules/mysql.js +0 -35
  294. package/lib/modules/sqlite3.js +0 -27
  295. package/lib/patch.js +0 -271
@@ -0,0 +1,516 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const PendingOperation_1 = require("./PendingOperation");
4
+ const Resource_1 = require("./Resource");
5
+ const utils_1 = require("./utils");
6
+ const events_1 = require("events");
7
+ const timers_1 = require("timers");
8
+ class Pool {
9
+ constructor(opt) {
10
+ this.destroyed = false;
11
+ this.emitter = new events_1.EventEmitter();
12
+ opt = opt || {};
13
+ if (!opt.create) {
14
+ throw new Error('Tarn: opt.create function most be provided');
15
+ }
16
+ if (!opt.destroy) {
17
+ throw new Error('Tarn: opt.destroy function most be provided');
18
+ }
19
+ if (typeof opt.min !== 'number' || opt.min < 0 || opt.min !== Math.round(opt.min)) {
20
+ throw new Error('Tarn: opt.min must be an integer >= 0');
21
+ }
22
+ if (typeof opt.max !== 'number' || opt.max <= 0 || opt.max !== Math.round(opt.max)) {
23
+ throw new Error('Tarn: opt.max must be an integer > 0');
24
+ }
25
+ if (opt.min > opt.max) {
26
+ throw new Error('Tarn: opt.max is smaller than opt.min');
27
+ }
28
+ if (!utils_1.checkOptionalTime(opt.acquireTimeoutMillis)) {
29
+ throw new Error('Tarn: invalid opt.acquireTimeoutMillis ' + JSON.stringify(opt.acquireTimeoutMillis));
30
+ }
31
+ if (!utils_1.checkOptionalTime(opt.createTimeoutMillis)) {
32
+ throw new Error('Tarn: invalid opt.createTimeoutMillis ' + JSON.stringify(opt.createTimeoutMillis));
33
+ }
34
+ if (!utils_1.checkOptionalTime(opt.destroyTimeoutMillis)) {
35
+ throw new Error('Tarn: invalid opt.destroyTimeoutMillis ' + JSON.stringify(opt.destroyTimeoutMillis));
36
+ }
37
+ if (!utils_1.checkOptionalTime(opt.idleTimeoutMillis)) {
38
+ throw new Error('Tarn: invalid opt.idleTimeoutMillis ' + JSON.stringify(opt.idleTimeoutMillis));
39
+ }
40
+ if (!utils_1.checkOptionalTime(opt.reapIntervalMillis)) {
41
+ throw new Error('Tarn: invalid opt.reapIntervalMillis ' + JSON.stringify(opt.reapIntervalMillis));
42
+ }
43
+ if (!utils_1.checkOptionalTime(opt.createRetryIntervalMillis)) {
44
+ throw new Error('Tarn: invalid opt.createRetryIntervalMillis ' +
45
+ JSON.stringify(opt.createRetryIntervalMillis));
46
+ }
47
+ const allowedKeys = {
48
+ create: true,
49
+ validate: true,
50
+ destroy: true,
51
+ log: true,
52
+ min: true,
53
+ max: true,
54
+ acquireTimeoutMillis: true,
55
+ createTimeoutMillis: true,
56
+ destroyTimeoutMillis: true,
57
+ idleTimeoutMillis: true,
58
+ reapIntervalMillis: true,
59
+ createRetryIntervalMillis: true,
60
+ propagateCreateError: true
61
+ };
62
+ for (const key of Object.keys(opt)) {
63
+ if (!allowedKeys[key]) {
64
+ throw new Error(`Tarn: unsupported option opt.${key}`);
65
+ }
66
+ }
67
+ this.creator = opt.create;
68
+ this.destroyer = opt.destroy;
69
+ this.validate = typeof opt.validate === 'function' ? opt.validate : () => true;
70
+ this.log = opt.log || (() => { });
71
+ this.acquireTimeoutMillis = opt.acquireTimeoutMillis || 30000;
72
+ this.createTimeoutMillis = opt.createTimeoutMillis || 30000;
73
+ this.destroyTimeoutMillis = opt.destroyTimeoutMillis || 5000;
74
+ this.idleTimeoutMillis = opt.idleTimeoutMillis || 30000;
75
+ this.reapIntervalMillis = opt.reapIntervalMillis || 1000;
76
+ this.createRetryIntervalMillis = opt.createRetryIntervalMillis || 200;
77
+ this.propagateCreateError = !!opt.propagateCreateError;
78
+ this.min = opt.min;
79
+ this.max = opt.max;
80
+ // All the resources, which are either already acquired or which are
81
+ // considered for being passed to acquire in async validation phase.
82
+ this.used = [];
83
+ // All the resources, which are either just created and free or returned
84
+ // back to pool after using.
85
+ this.free = [];
86
+ this.pendingCreates = [];
87
+ this.pendingAcquires = [];
88
+ this.pendingDestroys = [];
89
+ // When acquire is pending, but also still in validation phase
90
+ this.pendingValidations = [];
91
+ this.destroyed = false;
92
+ this.interval = null;
93
+ this.eventId = 1;
94
+ }
95
+ numUsed() {
96
+ return this.used.length;
97
+ }
98
+ numFree() {
99
+ return this.free.length;
100
+ }
101
+ numPendingAcquires() {
102
+ return this.pendingAcquires.length;
103
+ }
104
+ numPendingValidations() {
105
+ return this.pendingValidations.length;
106
+ }
107
+ numPendingCreates() {
108
+ return this.pendingCreates.length;
109
+ }
110
+ acquire() {
111
+ const eventId = this.eventId++;
112
+ this._executeEventHandlers('acquireRequest', eventId);
113
+ const pendingAcquire = new PendingOperation_1.PendingOperation(this.acquireTimeoutMillis);
114
+ this.pendingAcquires.push(pendingAcquire);
115
+ // If the acquire fails for whatever reason
116
+ // remove it from the pending queue.
117
+ pendingAcquire.promise = pendingAcquire.promise
118
+ .then(resource => {
119
+ this._executeEventHandlers('acquireSuccess', eventId, resource);
120
+ return resource;
121
+ })
122
+ .catch(err => {
123
+ this._executeEventHandlers('acquireFail', eventId, err);
124
+ remove(this.pendingAcquires, pendingAcquire);
125
+ return Promise.reject(err);
126
+ });
127
+ this._tryAcquireOrCreate();
128
+ return pendingAcquire;
129
+ }
130
+ release(resource) {
131
+ this._executeEventHandlers('release', resource);
132
+ for (let i = 0, l = this.used.length; i < l; ++i) {
133
+ const used = this.used[i];
134
+ if (used.resource === resource) {
135
+ this.used.splice(i, 1);
136
+ this.free.push(used.resolve());
137
+ this._tryAcquireOrCreate();
138
+ return true;
139
+ }
140
+ }
141
+ return false;
142
+ }
143
+ isEmpty() {
144
+ return ([
145
+ this.numFree(),
146
+ this.numUsed(),
147
+ this.numPendingAcquires(),
148
+ this.numPendingValidations(),
149
+ this.numPendingCreates()
150
+ ].reduce((total, value) => total + value) === 0);
151
+ }
152
+ /**
153
+ * Reaping cycle.
154
+ */
155
+ check() {
156
+ const timestamp = utils_1.now();
157
+ const newFree = [];
158
+ const minKeep = this.min - this.used.length;
159
+ const maxDestroy = this.free.length - minKeep;
160
+ let numDestroyed = 0;
161
+ this.free.forEach(free => {
162
+ if (utils_1.duration(timestamp, free.timestamp) >= this.idleTimeoutMillis &&
163
+ numDestroyed < maxDestroy) {
164
+ numDestroyed++;
165
+ this._destroy(free.resource);
166
+ }
167
+ else {
168
+ newFree.push(free);
169
+ }
170
+ });
171
+ this.free = newFree;
172
+ // Pool is completely empty, stop reaping.
173
+ // Next .acquire will start reaping interval again.
174
+ if (this.isEmpty()) {
175
+ this._stopReaping();
176
+ }
177
+ }
178
+ destroy() {
179
+ const eventId = this.eventId++;
180
+ this._executeEventHandlers('poolDestroyRequest', eventId);
181
+ this._stopReaping();
182
+ this.destroyed = true;
183
+ // First wait for all the pending creates get ready.
184
+ return utils_1.reflect(Promise.all(this.pendingCreates.map(create => utils_1.reflect(create.promise)))
185
+ .then(() => {
186
+ // eslint-disable-next-line
187
+ return new Promise((resolve, reject) => {
188
+ // poll every 100ms and wait that all validations are ready
189
+ if (this.numPendingValidations() === 0) {
190
+ resolve();
191
+ return;
192
+ }
193
+ const interval = setInterval(() => {
194
+ if (this.numPendingValidations() === 0) {
195
+ timers_1.clearInterval(interval);
196
+ resolve();
197
+ }
198
+ }, 100);
199
+ });
200
+ })
201
+ .then(() => {
202
+ // Wait for all the used resources to be freed.
203
+ return Promise.all(this.used.map(used => utils_1.reflect(used.promise)));
204
+ })
205
+ .then(() => {
206
+ // Abort all pending acquires.
207
+ return Promise.all(this.pendingAcquires.map(acquire => {
208
+ acquire.abort();
209
+ return utils_1.reflect(acquire.promise);
210
+ }));
211
+ })
212
+ .then(() => {
213
+ // Now we can destroy all the freed resources.
214
+ return Promise.all(this.free.map(free => utils_1.reflect(this._destroy(free.resource))));
215
+ })
216
+ .then(() => {
217
+ // Also wait rest of the pending destroys to finish
218
+ return Promise.all(this.pendingDestroys.map(pd => pd.promise));
219
+ })
220
+ .then(() => {
221
+ this.free = [];
222
+ this.pendingAcquires = [];
223
+ })).then(res => {
224
+ this._executeEventHandlers('poolDestroySuccess', eventId);
225
+ this.emitter.removeAllListeners();
226
+ return res;
227
+ });
228
+ }
229
+ on(event, listener) {
230
+ this.emitter.on(event, listener);
231
+ }
232
+ removeListener(event, listener) {
233
+ this.emitter.removeListener(event, listener);
234
+ }
235
+ removeAllListeners(event) {
236
+ this.emitter.removeAllListeners(event);
237
+ }
238
+ /**
239
+ * The most important method that is called always when resources
240
+ * are created / destroyed / acquired / released. In other words
241
+ * every time when resources are moved from used to free or vice
242
+ * versa.
243
+ *
244
+ * Either assigns free resources to pendingAcquires or creates new
245
+ * resources if there is room for it in the pool.
246
+ */
247
+ _tryAcquireOrCreate() {
248
+ if (this.destroyed) {
249
+ return;
250
+ }
251
+ if (this._hasFreeResources()) {
252
+ this._doAcquire();
253
+ }
254
+ else if (this._shouldCreateMoreResources()) {
255
+ this._doCreate();
256
+ }
257
+ }
258
+ _hasFreeResources() {
259
+ return this.free.length > 0;
260
+ }
261
+ _doAcquire() {
262
+ // Acquire as many pending acquires as possible concurrently
263
+ while (this._canAcquire()) {
264
+ // To allow async validation, we actually need to move free resource
265
+ // and pending acquire temporary from their respective arrays and depending
266
+ // on validation result to either leave the free resource to used resources array
267
+ // or destroy the free resource if validation did fail.
268
+ const pendingAcquire = this.pendingAcquires.shift();
269
+ const free = this.free.pop();
270
+ if (free === undefined || pendingAcquire === undefined) {
271
+ const errMessage = 'this.free was empty while trying to acquire resource';
272
+ this.log(`Tarn: ${errMessage}`, 'warn');
273
+ throw new Error(`Internal error, should never happen. ${errMessage}`);
274
+ }
275
+ // Make sure that pendingAcquire that is being validated is not lost and
276
+ // can be freed when pool is destroyed.
277
+ this.pendingValidations.push(pendingAcquire);
278
+ // Must be added here pre-emptively to prevent logic that decides
279
+ // if new resources are created will keep on working correctly.
280
+ this.used.push(free);
281
+ // if acquire fails also pending validation, must be aborted so that pre reserved
282
+ // resource will be returned to free resources immediately
283
+ const abortAbleValidation = new PendingOperation_1.PendingOperation(this.acquireTimeoutMillis);
284
+ // eslint-disable-next-line
285
+ pendingAcquire.promise.catch(err => {
286
+ abortAbleValidation.abort();
287
+ });
288
+ abortAbleValidation.promise
289
+ .catch(err => {
290
+ // There's nothing we can do here but log the error. This would otherwise
291
+ // leak out as an unhandled exception.
292
+ this.log('Tarn: resource validator threw an exception ' + err.stack, 'warn');
293
+ return false;
294
+ })
295
+ .then(validationSuccess => {
296
+ try {
297
+ if (validationSuccess && !pendingAcquire.isRejected) {
298
+ // At least one active resource exist, start reaping.
299
+ this._startReaping();
300
+ pendingAcquire.resolve(free.resource);
301
+ }
302
+ else {
303
+ remove(this.used, free);
304
+ // Only destroy the resource if the validation has failed
305
+ if (!validationSuccess) {
306
+ this._destroy(free.resource);
307
+ // Since we destroyed an invalid resource and were not able to fulfill
308
+ // all the pending acquires, we may need to create new ones or at
309
+ // least run this acquire loop again to verify it. But not immediately
310
+ // to prevent starving event loop.
311
+ setTimeout(() => {
312
+ this._tryAcquireOrCreate();
313
+ }, 0);
314
+ }
315
+ else {
316
+ this.free.push(free);
317
+ }
318
+ // is acquire was canceled, failed or timed out already
319
+ // no need to return it to pending queries
320
+ if (!pendingAcquire.isRejected) {
321
+ this.pendingAcquires.unshift(pendingAcquire);
322
+ }
323
+ }
324
+ }
325
+ finally {
326
+ remove(this.pendingValidations, pendingAcquire);
327
+ }
328
+ });
329
+ // try to validate
330
+ this._validateResource(free.resource)
331
+ .then(validationSuccess => {
332
+ abortAbleValidation.resolve(validationSuccess);
333
+ })
334
+ .catch(err => {
335
+ abortAbleValidation.reject(err);
336
+ });
337
+ }
338
+ }
339
+ _canAcquire() {
340
+ return this.free.length > 0 && this.pendingAcquires.length > 0;
341
+ }
342
+ _validateResource(resource) {
343
+ try {
344
+ return Promise.resolve(this.validate(resource));
345
+ }
346
+ catch (err) {
347
+ // prevent leaking of sync exception
348
+ return Promise.reject(err);
349
+ }
350
+ }
351
+ _shouldCreateMoreResources() {
352
+ return (this.used.length + this.pendingCreates.length < this.max &&
353
+ this.pendingCreates.length < this.pendingAcquires.length);
354
+ }
355
+ _doCreate() {
356
+ const pendingAcquiresBeforeCreate = this.pendingAcquires.slice();
357
+ const pendingCreate = this._create();
358
+ pendingCreate.promise
359
+ .then(() => {
360
+ // Not returned on purpose.
361
+ this._tryAcquireOrCreate();
362
+ return null;
363
+ })
364
+ .catch(err => {
365
+ if (this.propagateCreateError && this.pendingAcquires.length !== 0) {
366
+ // If propagateCreateError is true, we don't retry the create
367
+ // but reject the first pending acquire immediately. Intentionally
368
+ // use `this.pendingAcquires` instead of `pendingAcquiresBeforeCreate`
369
+ // in case some acquires in pendingAcquiresBeforeCreate have already
370
+ // been resolved.
371
+ this.pendingAcquires[0].reject(err);
372
+ }
373
+ // Save the create error to all pending acquires so that we can use it
374
+ // as the error to reject the acquire if it times out.
375
+ pendingAcquiresBeforeCreate.forEach(pendingAcquire => {
376
+ pendingAcquire.possibleTimeoutCause = err;
377
+ });
378
+ // Not returned on purpose.
379
+ utils_1.delay(this.createRetryIntervalMillis).then(() => this._tryAcquireOrCreate());
380
+ });
381
+ }
382
+ _create() {
383
+ const eventId = this.eventId++;
384
+ this._executeEventHandlers('createRequest', eventId);
385
+ const pendingCreate = new PendingOperation_1.PendingOperation(this.createTimeoutMillis);
386
+ // If an error occurs (likely a create timeout) remove this creation from
387
+ // the list of pending creations so we try to create a new one.
388
+ pendingCreate.promise = pendingCreate.promise.catch(err => {
389
+ if (remove(this.pendingCreates, pendingCreate)) {
390
+ // TODO: figure out more consistent way for different error handlers in next rewrite
391
+ this._executeEventHandlers('createFail', eventId, err);
392
+ }
393
+ throw err;
394
+ });
395
+ this.pendingCreates.push(pendingCreate);
396
+ callbackOrPromise(this.creator)
397
+ .then(resource => {
398
+ if (pendingCreate.isRejected) {
399
+ this.destroyer(resource);
400
+ return null;
401
+ }
402
+ remove(this.pendingCreates, pendingCreate);
403
+ this.free.push(new Resource_1.Resource(resource));
404
+ // Not returned on purpose.
405
+ pendingCreate.resolve(resource);
406
+ this._executeEventHandlers('createSuccess', eventId, resource);
407
+ return null;
408
+ })
409
+ .catch(err => {
410
+ if (pendingCreate.isRejected) {
411
+ return null;
412
+ }
413
+ if (remove(this.pendingCreates, pendingCreate)) {
414
+ this._executeEventHandlers('createFail', eventId, err);
415
+ }
416
+ // Not returned on purpose.
417
+ pendingCreate.reject(err);
418
+ return null;
419
+ });
420
+ return pendingCreate;
421
+ }
422
+ _destroy(resource) {
423
+ const eventId = this.eventId++;
424
+ this._executeEventHandlers('destroyRequest', eventId, resource);
425
+ // this.destroyer can be both synchronous and asynchronous.
426
+ // so we wrap it to promise to get all exceptions through same pipeline
427
+ const pendingDestroy = new PendingOperation_1.PendingOperation(this.destroyTimeoutMillis);
428
+ const retVal = Promise.resolve().then(() => this.destroyer(resource));
429
+ retVal
430
+ .then(() => {
431
+ pendingDestroy.resolve(resource);
432
+ })
433
+ .catch((err) => {
434
+ pendingDestroy.reject(err);
435
+ });
436
+ this.pendingDestroys.push(pendingDestroy);
437
+ // In case of an error there's nothing we can do here but log it.
438
+ return pendingDestroy.promise
439
+ .then(res => {
440
+ this._executeEventHandlers('destroySuccess', eventId, resource);
441
+ return res;
442
+ })
443
+ .catch(err => this._logDestroyerError(eventId, resource, err))
444
+ .then(res => {
445
+ const index = this.pendingDestroys.findIndex(pd => pd === pendingDestroy);
446
+ this.pendingDestroys.splice(index, 1);
447
+ return res;
448
+ });
449
+ }
450
+ _logDestroyerError(eventId, resource, err) {
451
+ this._executeEventHandlers('destroyFail', eventId, resource, err);
452
+ this.log('Tarn: resource destroyer threw an exception ' + err.stack, 'warn');
453
+ }
454
+ _startReaping() {
455
+ if (!this.interval) {
456
+ this._executeEventHandlers('startReaping');
457
+ this.interval = setInterval(() => this.check(), this.reapIntervalMillis);
458
+ }
459
+ }
460
+ _stopReaping() {
461
+ if (this.interval !== null) {
462
+ this._executeEventHandlers('stopReaping');
463
+ timers_1.clearInterval(this.interval);
464
+ }
465
+ this.interval = null;
466
+ }
467
+ _executeEventHandlers(eventName, ...args) {
468
+ const listeners = this.emitter.listeners(eventName);
469
+ // just calling .emit() would stop running rest of the listeners if one them fails
470
+ listeners.forEach(listener => {
471
+ try {
472
+ listener(...args);
473
+ }
474
+ catch (err) {
475
+ // There's nothing we can do here but log the error. This would otherwise
476
+ // leak out as an unhandled exception.
477
+ this.log(`Tarn: event handler "${eventName}" threw an exception ${err.stack}`, 'warn');
478
+ }
479
+ });
480
+ }
481
+ }
482
+ exports.Pool = Pool;
483
+ function remove(arr, item) {
484
+ const idx = arr.indexOf(item);
485
+ if (idx === -1) {
486
+ return false;
487
+ }
488
+ else {
489
+ arr.splice(idx, 1);
490
+ return true;
491
+ }
492
+ }
493
+ function callbackOrPromise(func) {
494
+ return new Promise((resolve, reject) => {
495
+ const callback = (err, resource) => {
496
+ if (err) {
497
+ reject(err);
498
+ }
499
+ else {
500
+ resolve(resource);
501
+ }
502
+ };
503
+ utils_1.tryPromise(() => func(callback))
504
+ .then(res => {
505
+ // If the result is falsy, we assume that the callback will
506
+ // be called instead of interpreting the falsy value as a
507
+ // result value.
508
+ if (res) {
509
+ resolve(res);
510
+ }
511
+ })
512
+ .catch(err => {
513
+ reject(err);
514
+ });
515
+ });
516
+ }
@@ -0,0 +1,16 @@
1
+ export declare type PromiseInspectionArgs<T> = {
2
+ value: T;
3
+ error?: Error;
4
+ } | {
5
+ value?: T;
6
+ error: Error;
7
+ };
8
+ export declare class PromiseInspection<T> {
9
+ _value: T | void;
10
+ _error: Error | void;
11
+ constructor(args: PromiseInspectionArgs<T>);
12
+ value(): void | T;
13
+ reason(): void | Error;
14
+ isRejected(): boolean;
15
+ isFulfilled(): boolean;
16
+ }
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ class PromiseInspection {
4
+ constructor(args) {
5
+ this._value = args.value;
6
+ this._error = args.error;
7
+ }
8
+ value() {
9
+ return this._value;
10
+ }
11
+ reason() {
12
+ return this._error;
13
+ }
14
+ isRejected() {
15
+ return !!this._error;
16
+ }
17
+ isFulfilled() {
18
+ return !!this._value;
19
+ }
20
+ }
21
+ exports.PromiseInspection = PromiseInspection;
@@ -0,0 +1,9 @@
1
+ import { Deferred } from './utils';
2
+ export declare class Resource<T> {
3
+ resource: T;
4
+ readonly timestamp: number;
5
+ protected deferred: Deferred<void>;
6
+ constructor(resource: T);
7
+ get promise(): Promise<void>;
8
+ resolve(): Resource<T>;
9
+ }
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const utils_1 = require("./utils");
4
+ class Resource {
5
+ constructor(resource) {
6
+ this.resource = resource;
7
+ this.resource = resource;
8
+ this.timestamp = utils_1.now();
9
+ this.deferred = utils_1.defer();
10
+ }
11
+ get promise() {
12
+ return this.deferred.promise;
13
+ }
14
+ resolve() {
15
+ this.deferred.resolve(undefined);
16
+ return new Resource(this.resource);
17
+ }
18
+ }
19
+ exports.Resource = Resource;
@@ -0,0 +1,2 @@
1
+ export declare class TimeoutError extends Error {
2
+ }
@@ -0,0 +1,5 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ class TimeoutError extends Error {
4
+ }
5
+ exports.TimeoutError = TimeoutError;
@@ -0,0 +1,3 @@
1
+ import { Pool } from './Pool';
2
+ import { TimeoutError } from './TimeoutError';
3
+ export { Pool, TimeoutError };
@@ -0,0 +1,10 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const Pool_1 = require("./Pool");
4
+ exports.Pool = Pool_1.Pool;
5
+ const TimeoutError_1 = require("./TimeoutError");
6
+ exports.TimeoutError = TimeoutError_1.TimeoutError;
7
+ module.exports = {
8
+ Pool: Pool_1.Pool,
9
+ TimeoutError: TimeoutError_1.TimeoutError
10
+ };
@@ -0,0 +1,14 @@
1
+ import { PromiseInspection } from './PromiseInspection';
2
+ export interface Deferred<T> {
3
+ resolve: (val: T) => any;
4
+ reject: <T>(err: T) => any;
5
+ promise: Promise<T>;
6
+ }
7
+ export declare function defer<T>(): Deferred<T>;
8
+ export declare function now(): number;
9
+ export declare function duration(t1: number, t2: number): number;
10
+ export declare function checkOptionalTime(time?: number): boolean;
11
+ export declare function checkRequiredTime(time: number): boolean;
12
+ export declare function delay(millis: number): Promise<unknown>;
13
+ export declare function reflect<T>(promise: Promise<T>): Promise<PromiseInspection<T> | PromiseInspection<unknown>>;
14
+ export declare function tryPromise<T>(cb: () => T | PromiseLike<T>): Promise<T>;
@@ -0,0 +1,60 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const PromiseInspection_1 = require("./PromiseInspection");
4
+ function defer() {
5
+ let resolve = null;
6
+ let reject = null;
7
+ const promise = new Promise((resolver, rejecter) => {
8
+ resolve = resolver;
9
+ reject = rejecter;
10
+ });
11
+ return {
12
+ promise,
13
+ resolve,
14
+ reject
15
+ };
16
+ }
17
+ exports.defer = defer;
18
+ function now() {
19
+ return Date.now();
20
+ }
21
+ exports.now = now;
22
+ function duration(t1, t2) {
23
+ return Math.abs(t2 - t1);
24
+ }
25
+ exports.duration = duration;
26
+ function checkOptionalTime(time) {
27
+ if (typeof time === 'undefined') {
28
+ return true;
29
+ }
30
+ return checkRequiredTime(time);
31
+ }
32
+ exports.checkOptionalTime = checkOptionalTime;
33
+ function checkRequiredTime(time) {
34
+ return typeof time === 'number' && time === Math.round(time) && time > 0;
35
+ }
36
+ exports.checkRequiredTime = checkRequiredTime;
37
+ function delay(millis) {
38
+ return new Promise(resolve => setTimeout(resolve, millis));
39
+ }
40
+ exports.delay = delay;
41
+ function reflect(promise) {
42
+ return promise
43
+ .then(value => {
44
+ return new PromiseInspection_1.PromiseInspection({ value });
45
+ })
46
+ .catch(error => {
47
+ return new PromiseInspection_1.PromiseInspection({ error });
48
+ });
49
+ }
50
+ exports.reflect = reflect;
51
+ function tryPromise(cb) {
52
+ try {
53
+ const result = cb();
54
+ return Promise.resolve(result);
55
+ }
56
+ catch (err) {
57
+ return Promise.reject(err);
58
+ }
59
+ }
60
+ exports.tryPromise = tryPromise;