@@ -33,6 +33,9 @@ export class Postgres implements IDatabase {
33
33
private poolRead : Pool ;
34
34
private lastPoolReadFail = 0 ;
35
35
36
+ private concurrentRequests = 0 ;
37
+ private concurrentReadRequests = 0 ;
38
+
36
39
constructor ( private config : DatabaseConfig ) { }
37
40
38
41
async init ( ) : Promise < void > {
@@ -99,8 +102,23 @@ export class Postgres implements IDatabase {
99
102
100
103
Logger . debug ( `prepare (postgres): type: ${ type } , query: ${ query } , params: ${ params } ` ) ;
101
104
102
- const pendingQueries : PromiseWithState < QueryResult < any > > [ ] = [ ] ;
105
+ if ( this . config . readOnly ) {
106
+ if ( this . concurrentReadRequests > this . config . postgresReadOnly ?. maxConcurrentRequests ) {
107
+ Logger . error ( `prepare (postgres): cancelling read query because too many concurrent requests, query: ${ query } ` ) ;
108
+ throw new Error ( "Too many concurrent requests" ) ;
109
+ }
110
+
111
+ this . concurrentReadRequests ++ ;
112
+ } else {
113
+ if ( this . concurrentRequests > this . config . postgres . maxConcurrentRequests ) {
114
+ Logger . error ( `prepare (postgres): cancelling query because too many concurrent requests, query: ${ query } ` ) ;
115
+ throw new Error ( "Too many concurrent requests" ) ;
116
+ }
117
+
118
+ this . concurrentRequests ++ ;
119
+ }
103
120
121
+ const pendingQueries : PromiseWithState < QueryResult < any > > [ ] = [ ] ;
104
122
let tries = 0 ;
105
123
let lastPool : Pool = null ;
106
124
const maxTries = ( ) => ( lastPool === this . pool
@@ -116,6 +134,12 @@ export class Postgres implements IDatabase {
116
134
if ( options . useReplica && maxTries ( ) - tries > 1 ) currentPromises . push ( savePromiseState ( timeoutPomise ( this . config . postgresReadOnly . readTimeout ) ) ) ;
117
135
const queryResult = await nextFulfilment ( currentPromises ) ;
118
136
137
+ if ( this . config . readOnly ) {
138
+ this . concurrentReadRequests -- ;
139
+ } else {
140
+ this . concurrentRequests -- ;
141
+ }
142
+
119
143
switch ( type ) {
120
144
case "get" : {
121
145
const value = queryResult . rows [ 0 ] ;
@@ -143,6 +167,12 @@ export class Postgres implements IDatabase {
143
167
}
144
168
} while ( this . isReadQuery ( type ) && tries < maxTries ( ) ) ;
145
169
170
+ if ( this . config . readOnly ) {
171
+ this . concurrentReadRequests -- ;
172
+ } else {
173
+ this . concurrentRequests -- ;
174
+ }
175
+
146
176
throw new Error ( `prepare (postgres): ${ type } ${ query } failed after ${ tries } tries` ) ;
147
177
}
148
178
0 commit comments