adaptic-backend 1.0.340 → 1.0.341

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 (110) hide show
  1. package/Account.cjs +2543 -2265
  2. package/Account.d.ts +19 -2
  3. package/Action.cjs +1116 -838
  4. package/Action.d.ts +19 -2
  5. package/Alert.cjs +2626 -2348
  6. package/Alert.d.ts +19 -2
  7. package/Allocation.cjs +2578 -2300
  8. package/Allocation.d.ts +19 -2
  9. package/AlpacaAccount.cjs +2383 -2105
  10. package/AlpacaAccount.d.ts +19 -2
  11. package/Asset.cjs +1813 -1535
  12. package/Asset.d.ts +19 -2
  13. package/Authenticator.cjs +2568 -2290
  14. package/Authenticator.d.ts +19 -2
  15. package/Customer.cjs +2495 -2217
  16. package/Customer.d.ts +19 -2
  17. package/EconomicEvent.cjs +645 -367
  18. package/EconomicEvent.d.ts +19 -2
  19. package/MarketSentiment.cjs +618 -340
  20. package/MarketSentiment.d.ts +19 -2
  21. package/NewsArticle.cjs +1933 -1655
  22. package/NewsArticle.d.ts +19 -2
  23. package/NewsArticleAssetSentiment.cjs +1842 -1564
  24. package/NewsArticleAssetSentiment.d.ts +19 -2
  25. package/ScheduledOptionOrder.cjs +594 -316
  26. package/ScheduledOptionOrder.d.ts +19 -2
  27. package/Session.cjs +2570 -2292
  28. package/Session.d.ts +19 -2
  29. package/Trade.cjs +1073 -795
  30. package/Trade.d.ts +19 -2
  31. package/User.cjs +2288 -2010
  32. package/User.d.ts +19 -2
  33. package/VerificationToken.cjs +606 -328
  34. package/VerificationToken.d.ts +19 -2
  35. package/esm/Account.d.ts +19 -2
  36. package/esm/Account.d.ts.map +1 -1
  37. package/esm/Account.js.map +1 -1
  38. package/esm/Account.mjs +2534 -2263
  39. package/esm/Action.d.ts +19 -2
  40. package/esm/Action.d.ts.map +1 -1
  41. package/esm/Action.js.map +1 -1
  42. package/esm/Action.mjs +1107 -836
  43. package/esm/Alert.d.ts +19 -2
  44. package/esm/Alert.d.ts.map +1 -1
  45. package/esm/Alert.js.map +1 -1
  46. package/esm/Alert.mjs +2617 -2346
  47. package/esm/Allocation.d.ts +19 -2
  48. package/esm/Allocation.d.ts.map +1 -1
  49. package/esm/Allocation.js.map +1 -1
  50. package/esm/Allocation.mjs +2569 -2298
  51. package/esm/AlpacaAccount.d.ts +19 -2
  52. package/esm/AlpacaAccount.d.ts.map +1 -1
  53. package/esm/AlpacaAccount.js.map +1 -1
  54. package/esm/AlpacaAccount.mjs +2374 -2103
  55. package/esm/Asset.d.ts +19 -2
  56. package/esm/Asset.d.ts.map +1 -1
  57. package/esm/Asset.js.map +1 -1
  58. package/esm/Asset.mjs +1804 -1533
  59. package/esm/Authenticator.d.ts +19 -2
  60. package/esm/Authenticator.d.ts.map +1 -1
  61. package/esm/Authenticator.js.map +1 -1
  62. package/esm/Authenticator.mjs +2559 -2288
  63. package/esm/Customer.d.ts +19 -2
  64. package/esm/Customer.d.ts.map +1 -1
  65. package/esm/Customer.js.map +1 -1
  66. package/esm/Customer.mjs +2486 -2215
  67. package/esm/EconomicEvent.d.ts +19 -2
  68. package/esm/EconomicEvent.d.ts.map +1 -1
  69. package/esm/EconomicEvent.js.map +1 -1
  70. package/esm/EconomicEvent.mjs +636 -365
  71. package/esm/MarketSentiment.d.ts +19 -2
  72. package/esm/MarketSentiment.d.ts.map +1 -1
  73. package/esm/MarketSentiment.js.map +1 -1
  74. package/esm/MarketSentiment.mjs +609 -338
  75. package/esm/NewsArticle.d.ts +19 -2
  76. package/esm/NewsArticle.d.ts.map +1 -1
  77. package/esm/NewsArticle.js.map +1 -1
  78. package/esm/NewsArticle.mjs +1924 -1653
  79. package/esm/NewsArticleAssetSentiment.d.ts +19 -2
  80. package/esm/NewsArticleAssetSentiment.d.ts.map +1 -1
  81. package/esm/NewsArticleAssetSentiment.js.map +1 -1
  82. package/esm/NewsArticleAssetSentiment.mjs +1833 -1562
  83. package/esm/ScheduledOptionOrder.d.ts +19 -2
  84. package/esm/ScheduledOptionOrder.d.ts.map +1 -1
  85. package/esm/ScheduledOptionOrder.js.map +1 -1
  86. package/esm/ScheduledOptionOrder.mjs +585 -314
  87. package/esm/Session.d.ts +19 -2
  88. package/esm/Session.d.ts.map +1 -1
  89. package/esm/Session.js.map +1 -1
  90. package/esm/Session.mjs +2561 -2290
  91. package/esm/Trade.d.ts +19 -2
  92. package/esm/Trade.d.ts.map +1 -1
  93. package/esm/Trade.js.map +1 -1
  94. package/esm/Trade.mjs +1064 -793
  95. package/esm/User.d.ts +19 -2
  96. package/esm/User.d.ts.map +1 -1
  97. package/esm/User.js.map +1 -1
  98. package/esm/User.mjs +2279 -2008
  99. package/esm/VerificationToken.d.ts +19 -2
  100. package/esm/VerificationToken.d.ts.map +1 -1
  101. package/esm/VerificationToken.js.map +1 -1
  102. package/esm/VerificationToken.mjs +597 -326
  103. package/esm/prismaClient.d.ts +4 -5
  104. package/esm/prismaClient.d.ts.map +1 -1
  105. package/esm/prismaClient.js.map +1 -1
  106. package/esm/prismaClient.mjs +13 -11
  107. package/package.json +1 -1
  108. package/prismaClient.cjs +13 -11
  109. package/prismaClient.d.ts +4 -5
  110. package/server.cjs +37 -5
package/Trade.cjs CHANGED
@@ -55,896 +55,1174 @@ exports.Trade = {
55
55
  * @param client - Apollo Client instance.
56
56
  * @returns The created Trade or null.
57
57
  */
58
+ /**
59
+ * Create a new Trade record.
60
+ * Enhanced with connection resilience against Prisma connection errors.
61
+ * @param props - Properties for the new record.
62
+ * @param globalClient - Apollo Client instance.
63
+ * @returns The created Trade or null.
64
+ */
58
65
  async create(props, globalClient) {
59
- const [modules, client] = await Promise.all([
60
- (0, client_1.getApolloModules)(),
61
- globalClient
62
- ? Promise.resolve(globalClient)
63
- : client_1.client
64
- ]);
65
- const { gql, ApolloError } = modules;
66
- const CREATE_ONE_TRADE = gql `
67
- mutation createOneTrade($data: TradeCreateInput!) {
68
- createOneTrade(data: $data) {
69
- ${selectionSet}
70
- }
71
- }
72
- `;
73
- const variables = {
74
- data: {
75
- alpacaAccountId: props.alpacaAccountId !== undefined ? props.alpacaAccountId : undefined,
76
- signal: props.signal !== undefined ? props.signal : undefined,
77
- strategy: props.strategy !== undefined ? props.strategy : undefined,
78
- analysis: props.analysis !== undefined ? props.analysis : undefined,
79
- summary: props.summary !== undefined ? props.summary : undefined,
80
- confidence: props.confidence !== undefined ? props.confidence : undefined,
81
- timestamp: props.timestamp !== undefined ? props.timestamp : undefined,
82
- status: props.status !== undefined ? props.status : undefined,
83
- symbol: props.symbol !== undefined ? props.symbol : undefined,
84
- entryPrice: props.entryPrice !== undefined ? props.entryPrice : undefined,
85
- exitPrice: props.exitPrice !== undefined ? props.exitPrice : undefined,
86
- entryQty: props.entryQty !== undefined ? props.entryQty : undefined,
87
- exitQty: props.exitQty !== undefined ? props.exitQty : undefined,
88
- entryValue: props.entryValue !== undefined ? props.entryValue : undefined,
89
- exitValue: props.exitValue !== undefined ? props.exitValue : undefined,
90
- entryTime: props.entryTime !== undefined ? props.entryTime : undefined,
91
- exitTime: props.exitTime !== undefined ? props.exitTime : undefined,
92
- pnlAmount: props.pnlAmount !== undefined ? props.pnlAmount : undefined,
93
- pnlPercent: props.pnlPercent !== undefined ? props.pnlPercent : undefined,
94
- durationMinutes: props.durationMinutes !== undefined ? props.durationMinutes : undefined,
95
- marketPhase: props.marketPhase !== undefined ? props.marketPhase : undefined,
96
- marketVolatility: props.marketVolatility !== undefined ? props.marketVolatility : undefined,
97
- thresholdsJson: props.thresholdsJson !== undefined ? props.thresholdsJson : undefined,
98
- actions: props.actions ?
99
- Array.isArray(props.actions) && props.actions.length > 0 && props.actions.every((item) => typeof item === 'object' && 'id' in item && Object.keys(item).length === 1) ? {
100
- connect: props.actions.map((item) => ({
101
- id: item.id
102
- }))
103
- }
104
- : { connectOrCreate: props.actions.map((item) => ({
105
- where: {
106
- id: item.id !== undefined ? item.id : undefined,
107
- alpacaOrderId: item.alpacaOrderId !== undefined ? item.alpacaOrderId : undefined,
108
- tradeId: item.tradeId !== undefined ? {
109
- equals: item.tradeId
110
- } : undefined,
111
- },
112
- create: {
113
- sequence: item.sequence !== undefined ? item.sequence : undefined,
114
- type: item.type !== undefined ? item.type : undefined,
115
- primary: item.primary !== undefined ? item.primary : undefined,
116
- note: item.note !== undefined ? item.note : undefined,
117
- status: item.status !== undefined ? item.status : undefined,
118
- alpacaOrderId: item.alpacaOrderId !== undefined ? item.alpacaOrderId : undefined,
119
- },
120
- }))
121
- } : undefined,
122
- },
123
- };
124
- const filteredVariables = (0, utils_1.removeUndefinedProps)(variables);
125
- try {
126
- const response = await client.mutate({ mutation: CREATE_ONE_TRADE, variables: filteredVariables });
127
- if (response.errors && response.errors.length > 0)
128
- throw new Error(response.errors[0].message);
129
- if (response && response.data && response.data.createOneTrade) {
130
- return response.data.createOneTrade;
66
+ var _a, _b, _c, _d, _e;
67
+ // Maximum number of retries for database connection issues
68
+ const MAX_RETRIES = 3;
69
+ let retryCount = 0;
70
+ let lastError = null;
71
+ // Retry loop to handle potential database connection issues
72
+ while (retryCount < MAX_RETRIES) {
73
+ try {
74
+ const [modules, client] = await Promise.all([
75
+ (0, client_1.getApolloModules)(),
76
+ globalClient
77
+ ? Promise.resolve(globalClient)
78
+ : client_1.client
79
+ ]);
80
+ const { gql, ApolloError } = modules;
81
+ const CREATE_ONE_TRADE = gql `
82
+ mutation createOneTrade($data: TradeCreateInput!) {
83
+ createOneTrade(data: $data) {
84
+ ${selectionSet}
85
+ }
86
+ }
87
+ `;
88
+ const variables = {
89
+ data: {
90
+ alpacaAccountId: props.alpacaAccountId !== undefined ? props.alpacaAccountId : undefined,
91
+ signal: props.signal !== undefined ? props.signal : undefined,
92
+ strategy: props.strategy !== undefined ? props.strategy : undefined,
93
+ analysis: props.analysis !== undefined ? props.analysis : undefined,
94
+ summary: props.summary !== undefined ? props.summary : undefined,
95
+ confidence: props.confidence !== undefined ? props.confidence : undefined,
96
+ timestamp: props.timestamp !== undefined ? props.timestamp : undefined,
97
+ status: props.status !== undefined ? props.status : undefined,
98
+ symbol: props.symbol !== undefined ? props.symbol : undefined,
99
+ entryPrice: props.entryPrice !== undefined ? props.entryPrice : undefined,
100
+ exitPrice: props.exitPrice !== undefined ? props.exitPrice : undefined,
101
+ entryQty: props.entryQty !== undefined ? props.entryQty : undefined,
102
+ exitQty: props.exitQty !== undefined ? props.exitQty : undefined,
103
+ entryValue: props.entryValue !== undefined ? props.entryValue : undefined,
104
+ exitValue: props.exitValue !== undefined ? props.exitValue : undefined,
105
+ entryTime: props.entryTime !== undefined ? props.entryTime : undefined,
106
+ exitTime: props.exitTime !== undefined ? props.exitTime : undefined,
107
+ pnlAmount: props.pnlAmount !== undefined ? props.pnlAmount : undefined,
108
+ pnlPercent: props.pnlPercent !== undefined ? props.pnlPercent : undefined,
109
+ durationMinutes: props.durationMinutes !== undefined ? props.durationMinutes : undefined,
110
+ marketPhase: props.marketPhase !== undefined ? props.marketPhase : undefined,
111
+ marketVolatility: props.marketVolatility !== undefined ? props.marketVolatility : undefined,
112
+ thresholdsJson: props.thresholdsJson !== undefined ? props.thresholdsJson : undefined,
113
+ actions: props.actions ?
114
+ Array.isArray(props.actions) && props.actions.length > 0 && props.actions.every((item) => typeof item === 'object' && 'id' in item && Object.keys(item).length === 1) ? {
115
+ connect: props.actions.map((item) => ({
116
+ id: item.id
117
+ }))
118
+ }
119
+ : { connectOrCreate: props.actions.map((item) => ({
120
+ where: {
121
+ id: item.id !== undefined ? item.id : undefined,
122
+ alpacaOrderId: item.alpacaOrderId !== undefined ? item.alpacaOrderId : undefined,
123
+ tradeId: item.tradeId !== undefined ? {
124
+ equals: item.tradeId
125
+ } : undefined,
126
+ },
127
+ create: {
128
+ sequence: item.sequence !== undefined ? item.sequence : undefined,
129
+ type: item.type !== undefined ? item.type : undefined,
130
+ primary: item.primary !== undefined ? item.primary : undefined,
131
+ note: item.note !== undefined ? item.note : undefined,
132
+ status: item.status !== undefined ? item.status : undefined,
133
+ alpacaOrderId: item.alpacaOrderId !== undefined ? item.alpacaOrderId : undefined,
134
+ },
135
+ }))
136
+ } : undefined,
137
+ },
138
+ };
139
+ const filteredVariables = (0, utils_1.removeUndefinedProps)(variables);
140
+ const response = await client.mutate({
141
+ mutation: CREATE_ONE_TRADE,
142
+ variables: filteredVariables,
143
+ // Don't cache mutations, but ensure we're using the freshest context
144
+ fetchPolicy: 'no-cache'
145
+ });
146
+ if (response.errors && response.errors.length > 0)
147
+ throw new Error(response.errors[0].message);
148
+ if (response && response.data && response.data.createOneTrade) {
149
+ return response.data.createOneTrade;
150
+ }
151
+ else {
152
+ return null;
153
+ }
131
154
  }
132
- else {
133
- return null;
155
+ catch (error) {
156
+ lastError = error;
157
+ // Check if this is a database connection error that we should retry
158
+ const isConnectionError = ((_a = error.message) === null || _a === void 0 ? void 0 : _a.includes('Server has closed the connection')) ||
159
+ ((_b = error.message) === null || _b === void 0 ? void 0 : _b.includes('Cannot reach database server')) ||
160
+ ((_c = error.message) === null || _c === void 0 ? void 0 : _c.includes('Connection timed out')) ||
161
+ ((_d = error.message) === null || _d === void 0 ? void 0 : _d.includes('Accelerate')) || // Prisma Accelerate proxy errors
162
+ (error.networkError && ((_e = error.networkError.message) === null || _e === void 0 ? void 0 : _e.includes('Failed to fetch')));
163
+ if (isConnectionError && retryCount < MAX_RETRIES - 1) {
164
+ retryCount++;
165
+ const delay = Math.pow(2, retryCount) * 100; // Exponential backoff: 200ms, 400ms, 800ms
166
+ console.warn("Database connection error, retrying...");
167
+ await new Promise(resolve => setTimeout(resolve, delay));
168
+ continue;
169
+ }
170
+ // Log the error and rethrow
171
+ console.error("Database error occurred:", error);
172
+ throw error;
134
173
  }
135
174
  }
136
- catch (error) {
137
- console.error('Error in createOneTrade:', error);
138
- throw error;
139
- }
175
+ // If we exhausted retries, throw the last error
176
+ throw lastError;
140
177
  },
141
178
  /**
142
179
  * Create multiple Trade records.
180
+ * Enhanced with connection resilience against Prisma connection errors.
143
181
  * @param props - Array of Trade objects for the new records.
144
182
  * @param globalClient - Apollo Client instance.
145
183
  * @returns The count of created records or null.
146
184
  */
147
185
  async createMany(props, globalClient) {
148
- const [modules, client] = await Promise.all([
149
- (0, client_1.getApolloModules)(),
150
- globalClient
151
- ? Promise.resolve(globalClient)
152
- : client_1.client
153
- ]);
154
- const { gql, ApolloError } = modules;
155
- const CREATE_MANY_TRADE = gql `
156
- mutation createManyTrade($data: [TradeCreateManyInput!]!) {
157
- createManyTrade(data: $data) {
158
- count
159
- }
160
- }`;
161
- const variables = {
162
- data: props.map(prop => ({
163
- alpacaAccountId: prop.alpacaAccountId !== undefined ? prop.alpacaAccountId : undefined,
164
- signal: prop.signal !== undefined ? prop.signal : undefined,
165
- strategy: prop.strategy !== undefined ? prop.strategy : undefined,
166
- analysis: prop.analysis !== undefined ? prop.analysis : undefined,
167
- summary: prop.summary !== undefined ? prop.summary : undefined,
168
- confidence: prop.confidence !== undefined ? prop.confidence : undefined,
169
- timestamp: prop.timestamp !== undefined ? prop.timestamp : undefined,
170
- status: prop.status !== undefined ? prop.status : undefined,
171
- symbol: prop.symbol !== undefined ? prop.symbol : undefined,
172
- entryPrice: prop.entryPrice !== undefined ? prop.entryPrice : undefined,
173
- exitPrice: prop.exitPrice !== undefined ? prop.exitPrice : undefined,
174
- entryQty: prop.entryQty !== undefined ? prop.entryQty : undefined,
175
- exitQty: prop.exitQty !== undefined ? prop.exitQty : undefined,
176
- entryValue: prop.entryValue !== undefined ? prop.entryValue : undefined,
177
- exitValue: prop.exitValue !== undefined ? prop.exitValue : undefined,
178
- entryTime: prop.entryTime !== undefined ? prop.entryTime : undefined,
179
- exitTime: prop.exitTime !== undefined ? prop.exitTime : undefined,
180
- pnlAmount: prop.pnlAmount !== undefined ? prop.pnlAmount : undefined,
181
- pnlPercent: prop.pnlPercent !== undefined ? prop.pnlPercent : undefined,
182
- durationMinutes: prop.durationMinutes !== undefined ? prop.durationMinutes : undefined,
183
- marketPhase: prop.marketPhase !== undefined ? prop.marketPhase : undefined,
184
- marketVolatility: prop.marketVolatility !== undefined ? prop.marketVolatility : undefined,
185
- thresholdsJson: prop.thresholdsJson !== undefined ? prop.thresholdsJson : undefined,
186
- })),
187
- };
188
- const filteredVariables = (0, utils_1.removeUndefinedProps)(variables);
189
- try {
190
- const response = await client.mutate({ mutation: CREATE_MANY_TRADE, variables: filteredVariables });
191
- if (response.errors && response.errors.length > 0)
192
- throw new Error(response.errors[0].message);
193
- if (response && response.data && response.data.createManyTrade) {
194
- return response.data.createManyTrade;
186
+ var _a, _b, _c, _d, _e;
187
+ // Maximum number of retries for database connection issues
188
+ const MAX_RETRIES = 3;
189
+ let retryCount = 0;
190
+ let lastError = null;
191
+ // Retry loop to handle potential database connection issues
192
+ while (retryCount < MAX_RETRIES) {
193
+ try {
194
+ const [modules, client] = await Promise.all([
195
+ (0, client_1.getApolloModules)(),
196
+ globalClient
197
+ ? Promise.resolve(globalClient)
198
+ : client_1.client
199
+ ]);
200
+ const { gql, ApolloError } = modules;
201
+ const CREATE_MANY_TRADE = gql `
202
+ mutation createManyTrade($data: [TradeCreateManyInput!]!) {
203
+ createManyTrade(data: $data) {
204
+ count
195
205
  }
196
- else {
197
- return null;
206
+ }`;
207
+ const variables = {
208
+ data: props.map(prop => ({
209
+ alpacaAccountId: prop.alpacaAccountId !== undefined ? prop.alpacaAccountId : undefined,
210
+ signal: prop.signal !== undefined ? prop.signal : undefined,
211
+ strategy: prop.strategy !== undefined ? prop.strategy : undefined,
212
+ analysis: prop.analysis !== undefined ? prop.analysis : undefined,
213
+ summary: prop.summary !== undefined ? prop.summary : undefined,
214
+ confidence: prop.confidence !== undefined ? prop.confidence : undefined,
215
+ timestamp: prop.timestamp !== undefined ? prop.timestamp : undefined,
216
+ status: prop.status !== undefined ? prop.status : undefined,
217
+ symbol: prop.symbol !== undefined ? prop.symbol : undefined,
218
+ entryPrice: prop.entryPrice !== undefined ? prop.entryPrice : undefined,
219
+ exitPrice: prop.exitPrice !== undefined ? prop.exitPrice : undefined,
220
+ entryQty: prop.entryQty !== undefined ? prop.entryQty : undefined,
221
+ exitQty: prop.exitQty !== undefined ? prop.exitQty : undefined,
222
+ entryValue: prop.entryValue !== undefined ? prop.entryValue : undefined,
223
+ exitValue: prop.exitValue !== undefined ? prop.exitValue : undefined,
224
+ entryTime: prop.entryTime !== undefined ? prop.entryTime : undefined,
225
+ exitTime: prop.exitTime !== undefined ? prop.exitTime : undefined,
226
+ pnlAmount: prop.pnlAmount !== undefined ? prop.pnlAmount : undefined,
227
+ pnlPercent: prop.pnlPercent !== undefined ? prop.pnlPercent : undefined,
228
+ durationMinutes: prop.durationMinutes !== undefined ? prop.durationMinutes : undefined,
229
+ marketPhase: prop.marketPhase !== undefined ? prop.marketPhase : undefined,
230
+ marketVolatility: prop.marketVolatility !== undefined ? prop.marketVolatility : undefined,
231
+ thresholdsJson: prop.thresholdsJson !== undefined ? prop.thresholdsJson : undefined,
232
+ })),
233
+ };
234
+ const filteredVariables = (0, utils_1.removeUndefinedProps)(variables);
235
+ const response = await client.mutate({
236
+ mutation: CREATE_MANY_TRADE,
237
+ variables: filteredVariables,
238
+ // Don't cache mutations, but ensure we're using the freshest context
239
+ fetchPolicy: 'no-cache'
240
+ });
241
+ if (response.errors && response.errors.length > 0)
242
+ throw new Error(response.errors[0].message);
243
+ if (response && response.data && response.data.createManyTrade) {
244
+ return response.data.createManyTrade;
245
+ }
246
+ else {
247
+ return null;
248
+ }
249
+ }
250
+ catch (error) {
251
+ lastError = error;
252
+ // Check if this is a database connection error that we should retry
253
+ const isConnectionError = ((_a = error.message) === null || _a === void 0 ? void 0 : _a.includes('Server has closed the connection')) ||
254
+ ((_b = error.message) === null || _b === void 0 ? void 0 : _b.includes('Cannot reach database server')) ||
255
+ ((_c = error.message) === null || _c === void 0 ? void 0 : _c.includes('Connection timed out')) ||
256
+ ((_d = error.message) === null || _d === void 0 ? void 0 : _d.includes('Accelerate')) || // Prisma Accelerate proxy errors
257
+ (error.networkError && ((_e = error.networkError.message) === null || _e === void 0 ? void 0 : _e.includes('Failed to fetch')));
258
+ if (isConnectionError && retryCount < MAX_RETRIES - 1) {
259
+ retryCount++;
260
+ const delay = Math.pow(2, retryCount) * 100; // Exponential backoff: 200ms, 400ms, 800ms
261
+ console.warn("Database connection error, retrying...");
262
+ await new Promise(resolve => setTimeout(resolve, delay));
263
+ continue;
264
+ }
265
+ // Log the error and rethrow
266
+ console.error("Database error occurred:", error);
267
+ throw error;
198
268
  }
199
269
  }
200
- catch (error) {
201
- console.error('Error in createManyTrade:', error);
202
- throw error;
203
- }
270
+ // If we exhausted retries, throw the last error
271
+ throw lastError;
204
272
  },
205
273
  /**
206
274
  * Update a single Trade record.
275
+ * Enhanced with connection resilience against Prisma connection errors.
207
276
  * @param props - Properties to update.
208
277
  * @param globalClient - Apollo Client instance.
209
278
  * @returns The updated Trade or null.
210
279
  */
211
280
  async update(props, globalClient) {
212
- const [modules, client] = await Promise.all([
213
- (0, client_1.getApolloModules)(),
214
- globalClient
215
- ? Promise.resolve(globalClient)
216
- : client_1.client
217
- ]);
218
- const { gql, ApolloError } = modules;
219
- const UPDATE_ONE_TRADE = gql `
220
- mutation updateOneTrade($data: TradeUpdateInput!, $where: TradeWhereUniqueInput!) {
221
- updateOneTrade(data: $data, where: $where) {
222
- ${selectionSet}
223
- }
224
- }`;
225
- const variables = {
226
- where: {
227
- id: props.id !== undefined ? props.id : undefined,
228
- alpacaAccountId: props.alpacaAccountId !== undefined ? {
229
- equals: props.alpacaAccountId
230
- } : undefined,
231
- symbol: props.symbol !== undefined ? {
232
- equals: props.symbol
233
- } : undefined,
234
- },
235
- data: {
236
- id: props.id !== undefined ? {
237
- set: props.id
238
- } : undefined,
239
- alpacaAccountId: props.alpacaAccountId !== undefined ? {
240
- set: props.alpacaAccountId
241
- } : undefined,
242
- signal: props.signal !== undefined ? {
243
- set: props.signal
244
- } : undefined,
245
- strategy: props.strategy !== undefined ? {
246
- set: props.strategy
247
- } : undefined,
248
- analysis: props.analysis !== undefined ? {
249
- set: props.analysis
250
- } : undefined,
251
- summary: props.summary !== undefined ? {
252
- set: props.summary
253
- } : undefined,
254
- confidence: props.confidence !== undefined ? {
255
- set: props.confidence
256
- } : undefined,
257
- timestamp: props.timestamp !== undefined ? {
258
- set: props.timestamp
259
- } : undefined,
260
- createdAt: props.createdAt !== undefined ? {
261
- set: props.createdAt
262
- } : undefined,
263
- updatedAt: props.updatedAt !== undefined ? {
264
- set: props.updatedAt
265
- } : undefined,
266
- status: props.status !== undefined ? {
267
- set: props.status
268
- } : undefined,
269
- symbol: props.symbol !== undefined ? {
270
- set: props.symbol
271
- } : undefined,
272
- entryPrice: props.entryPrice !== undefined ? {
273
- set: props.entryPrice
274
- } : undefined,
275
- exitPrice: props.exitPrice !== undefined ? {
276
- set: props.exitPrice
277
- } : undefined,
278
- entryQty: props.entryQty !== undefined ? {
279
- set: props.entryQty
280
- } : undefined,
281
- exitQty: props.exitQty !== undefined ? {
282
- set: props.exitQty
283
- } : undefined,
284
- entryValue: props.entryValue !== undefined ? {
285
- set: props.entryValue
286
- } : undefined,
287
- exitValue: props.exitValue !== undefined ? {
288
- set: props.exitValue
289
- } : undefined,
290
- entryTime: props.entryTime !== undefined ? {
291
- set: props.entryTime
292
- } : undefined,
293
- exitTime: props.exitTime !== undefined ? {
294
- set: props.exitTime
295
- } : undefined,
296
- pnlAmount: props.pnlAmount !== undefined ? {
297
- set: props.pnlAmount
298
- } : undefined,
299
- pnlPercent: props.pnlPercent !== undefined ? {
300
- set: props.pnlPercent
301
- } : undefined,
302
- durationMinutes: props.durationMinutes !== undefined ? {
303
- set: props.durationMinutes
304
- } : undefined,
305
- marketPhase: props.marketPhase !== undefined ? {
306
- set: props.marketPhase
307
- } : undefined,
308
- marketVolatility: props.marketVolatility !== undefined ? {
309
- set: props.marketVolatility
310
- } : undefined,
311
- thresholdsJson: props.thresholdsJson !== undefined ? {
312
- set: props.thresholdsJson
313
- } : undefined,
314
- actions: props.actions ?
315
- Array.isArray(props.actions) && props.actions.length > 0 && props.actions.every((item) => typeof item === 'object' && ('id' in item || 'symbol' in item) && Object.keys(item).length === 1) ? {
316
- connect: props.actions.map((item) => ({
317
- id: item.id
318
- }))
319
- } : { upsert: props.actions.map((item) => ({
320
- where: {
321
- id: item.id !== undefined ? item.id : undefined,
322
- alpacaOrderId: item.alpacaOrderId !== undefined ? item.alpacaOrderId : undefined,
323
- tradeId: item.tradeId !== undefined ? {
324
- equals: item.tradeId
325
- } : undefined,
326
- },
327
- update: {
328
- id: item.id !== undefined ? {
329
- set: item.id
330
- } : undefined,
331
- sequence: item.sequence !== undefined ? {
332
- set: item.sequence
333
- } : undefined,
334
- type: item.type !== undefined ? {
335
- set: item.type
336
- } : undefined,
337
- primary: item.primary !== undefined ? {
338
- set: item.primary
339
- } : undefined,
340
- note: item.note !== undefined ? {
341
- set: item.note
342
- } : undefined,
343
- status: item.status !== undefined ? {
344
- set: item.status
345
- } : undefined,
346
- alpacaOrderId: item.alpacaOrderId !== undefined ? {
347
- set: item.alpacaOrderId
348
- } : undefined,
349
- },
350
- create: {
351
- sequence: item.sequence !== undefined ? item.sequence : undefined,
352
- type: item.type !== undefined ? item.type : undefined,
353
- primary: item.primary !== undefined ? item.primary : undefined,
354
- note: item.note !== undefined ? item.note : undefined,
355
- status: item.status !== undefined ? item.status : undefined,
356
- alpacaOrderId: item.alpacaOrderId !== undefined ? item.alpacaOrderId : undefined,
357
- },
358
- }))
359
- } : undefined,
360
- },
361
- };
362
- const filteredVariables = (0, utils_1.removeUndefinedProps)(variables);
363
- try {
364
- const response = await client.mutate({ mutation: UPDATE_ONE_TRADE, variables: filteredVariables });
365
- if (response.errors && response.errors.length > 0)
366
- throw new Error(response.errors[0].message);
367
- if (response && response.data && response.data.updateOneTrade) {
368
- return response.data.updateOneTrade;
281
+ var _a, _b, _c, _d, _e;
282
+ // Maximum number of retries for database connection issues
283
+ const MAX_RETRIES = 3;
284
+ let retryCount = 0;
285
+ let lastError = null;
286
+ // Retry loop to handle potential database connection issues
287
+ while (retryCount < MAX_RETRIES) {
288
+ try {
289
+ const [modules, client] = await Promise.all([
290
+ (0, client_1.getApolloModules)(),
291
+ globalClient
292
+ ? Promise.resolve(globalClient)
293
+ : client_1.client
294
+ ]);
295
+ const { gql, ApolloError } = modules;
296
+ const UPDATE_ONE_TRADE = gql `
297
+ mutation updateOneTrade($data: TradeUpdateInput!, $where: TradeWhereUniqueInput!) {
298
+ updateOneTrade(data: $data, where: $where) {
299
+ ${selectionSet}
300
+ }
301
+ }`;
302
+ const variables = {
303
+ where: {
304
+ id: props.id !== undefined ? props.id : undefined,
305
+ alpacaAccountId: props.alpacaAccountId !== undefined ? {
306
+ equals: props.alpacaAccountId
307
+ } : undefined,
308
+ symbol: props.symbol !== undefined ? {
309
+ equals: props.symbol
310
+ } : undefined,
311
+ },
312
+ data: {
313
+ id: props.id !== undefined ? {
314
+ set: props.id
315
+ } : undefined,
316
+ alpacaAccountId: props.alpacaAccountId !== undefined ? {
317
+ set: props.alpacaAccountId
318
+ } : undefined,
319
+ signal: props.signal !== undefined ? {
320
+ set: props.signal
321
+ } : undefined,
322
+ strategy: props.strategy !== undefined ? {
323
+ set: props.strategy
324
+ } : undefined,
325
+ analysis: props.analysis !== undefined ? {
326
+ set: props.analysis
327
+ } : undefined,
328
+ summary: props.summary !== undefined ? {
329
+ set: props.summary
330
+ } : undefined,
331
+ confidence: props.confidence !== undefined ? {
332
+ set: props.confidence
333
+ } : undefined,
334
+ timestamp: props.timestamp !== undefined ? {
335
+ set: props.timestamp
336
+ } : undefined,
337
+ createdAt: props.createdAt !== undefined ? {
338
+ set: props.createdAt
339
+ } : undefined,
340
+ updatedAt: props.updatedAt !== undefined ? {
341
+ set: props.updatedAt
342
+ } : undefined,
343
+ status: props.status !== undefined ? {
344
+ set: props.status
345
+ } : undefined,
346
+ symbol: props.symbol !== undefined ? {
347
+ set: props.symbol
348
+ } : undefined,
349
+ entryPrice: props.entryPrice !== undefined ? {
350
+ set: props.entryPrice
351
+ } : undefined,
352
+ exitPrice: props.exitPrice !== undefined ? {
353
+ set: props.exitPrice
354
+ } : undefined,
355
+ entryQty: props.entryQty !== undefined ? {
356
+ set: props.entryQty
357
+ } : undefined,
358
+ exitQty: props.exitQty !== undefined ? {
359
+ set: props.exitQty
360
+ } : undefined,
361
+ entryValue: props.entryValue !== undefined ? {
362
+ set: props.entryValue
363
+ } : undefined,
364
+ exitValue: props.exitValue !== undefined ? {
365
+ set: props.exitValue
366
+ } : undefined,
367
+ entryTime: props.entryTime !== undefined ? {
368
+ set: props.entryTime
369
+ } : undefined,
370
+ exitTime: props.exitTime !== undefined ? {
371
+ set: props.exitTime
372
+ } : undefined,
373
+ pnlAmount: props.pnlAmount !== undefined ? {
374
+ set: props.pnlAmount
375
+ } : undefined,
376
+ pnlPercent: props.pnlPercent !== undefined ? {
377
+ set: props.pnlPercent
378
+ } : undefined,
379
+ durationMinutes: props.durationMinutes !== undefined ? {
380
+ set: props.durationMinutes
381
+ } : undefined,
382
+ marketPhase: props.marketPhase !== undefined ? {
383
+ set: props.marketPhase
384
+ } : undefined,
385
+ marketVolatility: props.marketVolatility !== undefined ? {
386
+ set: props.marketVolatility
387
+ } : undefined,
388
+ thresholdsJson: props.thresholdsJson !== undefined ? {
389
+ set: props.thresholdsJson
390
+ } : undefined,
391
+ actions: props.actions ?
392
+ Array.isArray(props.actions) && props.actions.length > 0 && props.actions.every((item) => typeof item === 'object' && ('id' in item || 'symbol' in item) && Object.keys(item).length === 1) ? {
393
+ connect: props.actions.map((item) => ({
394
+ id: item.id
395
+ }))
396
+ } : { upsert: props.actions.map((item) => ({
397
+ where: {
398
+ id: item.id !== undefined ? item.id : undefined,
399
+ alpacaOrderId: item.alpacaOrderId !== undefined ? item.alpacaOrderId : undefined,
400
+ tradeId: item.tradeId !== undefined ? {
401
+ equals: item.tradeId
402
+ } : undefined,
403
+ },
404
+ update: {
405
+ id: item.id !== undefined ? {
406
+ set: item.id
407
+ } : undefined,
408
+ sequence: item.sequence !== undefined ? {
409
+ set: item.sequence
410
+ } : undefined,
411
+ type: item.type !== undefined ? {
412
+ set: item.type
413
+ } : undefined,
414
+ primary: item.primary !== undefined ? {
415
+ set: item.primary
416
+ } : undefined,
417
+ note: item.note !== undefined ? {
418
+ set: item.note
419
+ } : undefined,
420
+ status: item.status !== undefined ? {
421
+ set: item.status
422
+ } : undefined,
423
+ alpacaOrderId: item.alpacaOrderId !== undefined ? {
424
+ set: item.alpacaOrderId
425
+ } : undefined,
426
+ },
427
+ create: {
428
+ sequence: item.sequence !== undefined ? item.sequence : undefined,
429
+ type: item.type !== undefined ? item.type : undefined,
430
+ primary: item.primary !== undefined ? item.primary : undefined,
431
+ note: item.note !== undefined ? item.note : undefined,
432
+ status: item.status !== undefined ? item.status : undefined,
433
+ alpacaOrderId: item.alpacaOrderId !== undefined ? item.alpacaOrderId : undefined,
434
+ },
435
+ }))
436
+ } : undefined,
437
+ },
438
+ };
439
+ const filteredVariables = (0, utils_1.removeUndefinedProps)(variables);
440
+ const response = await client.mutate({
441
+ mutation: UPDATE_ONE_TRADE,
442
+ variables: filteredVariables,
443
+ // Don't cache mutations, but ensure we're using the freshest context
444
+ fetchPolicy: 'no-cache'
445
+ });
446
+ if (response.errors && response.errors.length > 0)
447
+ throw new Error(response.errors[0].message);
448
+ if (response && response.data && response.data.updateOneTrade) {
449
+ return response.data.updateOneTrade;
450
+ }
451
+ else {
452
+ return null;
453
+ }
369
454
  }
370
- else {
371
- return null;
455
+ catch (error) {
456
+ lastError = error;
457
+ // Check if this is a database connection error that we should retry
458
+ const isConnectionError = ((_a = error.message) === null || _a === void 0 ? void 0 : _a.includes('Server has closed the connection')) ||
459
+ ((_b = error.message) === null || _b === void 0 ? void 0 : _b.includes('Cannot reach database server')) ||
460
+ ((_c = error.message) === null || _c === void 0 ? void 0 : _c.includes('Connection timed out')) ||
461
+ ((_d = error.message) === null || _d === void 0 ? void 0 : _d.includes('Accelerate')) || // Prisma Accelerate proxy errors
462
+ (error.networkError && ((_e = error.networkError.message) === null || _e === void 0 ? void 0 : _e.includes('Failed to fetch')));
463
+ if (isConnectionError && retryCount < MAX_RETRIES - 1) {
464
+ retryCount++;
465
+ const delay = Math.pow(2, retryCount) * 100; // Exponential backoff: 200ms, 400ms, 800ms
466
+ console.warn("Database connection error, retrying...");
467
+ await new Promise(resolve => setTimeout(resolve, delay));
468
+ continue;
469
+ }
470
+ // Log the error and rethrow
471
+ console.error("Database error occurred:", error);
472
+ throw error;
372
473
  }
373
474
  }
374
- catch (error) {
375
- console.error('Error in updateOneTrade:', error);
376
- throw error;
377
- }
475
+ // If we exhausted retries, throw the last error
476
+ throw lastError;
378
477
  },
379
478
  /**
380
479
  * Upsert a single Trade record.
480
+ * Enhanced with connection resilience against Prisma connection errors.
381
481
  * @param props - Properties to update.
382
482
  * @param globalClient - Apollo Client instance.
383
483
  * @returns The updated Trade or null.
384
484
  */
385
485
  async upsert(props, globalClient) {
386
- const [modules, client] = await Promise.all([
387
- (0, client_1.getApolloModules)(),
388
- globalClient
389
- ? Promise.resolve(globalClient)
390
- : client_1.client
391
- ]);
392
- const { gql, ApolloError } = modules;
393
- const UPSERT_ONE_TRADE = gql `
394
- mutation upsertOneTrade($where: TradeWhereUniqueInput!, $create: TradeCreateInput!, $update: TradeUpdateInput!) {
395
- upsertOneTrade(where: $where, create: $create, update: $update) {
396
- ${selectionSet}
397
- }
398
- }`;
399
- const variables = {
400
- where: {
401
- id: props.id !== undefined ? props.id : undefined,
402
- alpacaAccountId: props.alpacaAccountId !== undefined ? {
403
- equals: props.alpacaAccountId
404
- } : undefined,
405
- symbol: props.symbol !== undefined ? {
406
- equals: props.symbol
407
- } : undefined,
408
- },
409
- create: {
410
- alpacaAccountId: props.alpacaAccountId !== undefined ? props.alpacaAccountId : undefined,
411
- signal: props.signal !== undefined ? props.signal : undefined,
412
- strategy: props.strategy !== undefined ? props.strategy : undefined,
413
- analysis: props.analysis !== undefined ? props.analysis : undefined,
414
- summary: props.summary !== undefined ? props.summary : undefined,
415
- confidence: props.confidence !== undefined ? props.confidence : undefined,
416
- timestamp: props.timestamp !== undefined ? props.timestamp : undefined,
417
- status: props.status !== undefined ? props.status : undefined,
418
- symbol: props.symbol !== undefined ? props.symbol : undefined,
419
- entryPrice: props.entryPrice !== undefined ? props.entryPrice : undefined,
420
- exitPrice: props.exitPrice !== undefined ? props.exitPrice : undefined,
421
- entryQty: props.entryQty !== undefined ? props.entryQty : undefined,
422
- exitQty: props.exitQty !== undefined ? props.exitQty : undefined,
423
- entryValue: props.entryValue !== undefined ? props.entryValue : undefined,
424
- exitValue: props.exitValue !== undefined ? props.exitValue : undefined,
425
- entryTime: props.entryTime !== undefined ? props.entryTime : undefined,
426
- exitTime: props.exitTime !== undefined ? props.exitTime : undefined,
427
- pnlAmount: props.pnlAmount !== undefined ? props.pnlAmount : undefined,
428
- pnlPercent: props.pnlPercent !== undefined ? props.pnlPercent : undefined,
429
- durationMinutes: props.durationMinutes !== undefined ? props.durationMinutes : undefined,
430
- marketPhase: props.marketPhase !== undefined ? props.marketPhase : undefined,
431
- marketVolatility: props.marketVolatility !== undefined ? props.marketVolatility : undefined,
432
- thresholdsJson: props.thresholdsJson !== undefined ? props.thresholdsJson : undefined,
433
- actions: props.actions ?
434
- Array.isArray(props.actions) && props.actions.length > 0 && props.actions.every((item) => typeof item === 'object' && 'id' in item && Object.keys(item).length === 1) ? {
435
- connect: props.actions.map((item) => ({
436
- id: item.id
437
- }))
438
- }
439
- : { connectOrCreate: props.actions.map((item) => ({
440
- where: {
441
- id: item.id !== undefined ? item.id : undefined,
442
- alpacaOrderId: item.alpacaOrderId !== undefined ? item.alpacaOrderId : undefined,
443
- tradeId: item.tradeId !== undefined ? {
444
- equals: item.tradeId
445
- } : undefined,
446
- },
447
- create: {
448
- sequence: item.sequence !== undefined ? item.sequence : undefined,
449
- type: item.type !== undefined ? item.type : undefined,
450
- primary: item.primary !== undefined ? item.primary : undefined,
451
- note: item.note !== undefined ? item.note : undefined,
452
- status: item.status !== undefined ? item.status : undefined,
453
- alpacaOrderId: item.alpacaOrderId !== undefined ? item.alpacaOrderId : undefined,
454
- },
455
- }))
456
- } : undefined,
457
- },
458
- update: {
459
- alpacaAccountId: props.alpacaAccountId !== undefined ? {
460
- set: props.alpacaAccountId
461
- } : undefined,
462
- signal: props.signal !== undefined ? {
463
- set: props.signal
464
- } : undefined,
465
- strategy: props.strategy !== undefined ? {
466
- set: props.strategy
467
- } : undefined,
468
- analysis: props.analysis !== undefined ? {
469
- set: props.analysis
470
- } : undefined,
471
- summary: props.summary !== undefined ? {
472
- set: props.summary
473
- } : undefined,
474
- confidence: props.confidence !== undefined ? {
475
- set: props.confidence
476
- } : undefined,
477
- timestamp: props.timestamp !== undefined ? {
478
- set: props.timestamp
479
- } : undefined,
480
- status: props.status !== undefined ? {
481
- set: props.status
482
- } : undefined,
483
- symbol: props.symbol !== undefined ? {
484
- set: props.symbol
485
- } : undefined,
486
- entryPrice: props.entryPrice !== undefined ? {
487
- set: props.entryPrice
488
- } : undefined,
489
- exitPrice: props.exitPrice !== undefined ? {
490
- set: props.exitPrice
491
- } : undefined,
492
- entryQty: props.entryQty !== undefined ? {
493
- set: props.entryQty
494
- } : undefined,
495
- exitQty: props.exitQty !== undefined ? {
496
- set: props.exitQty
497
- } : undefined,
498
- entryValue: props.entryValue !== undefined ? {
499
- set: props.entryValue
500
- } : undefined,
501
- exitValue: props.exitValue !== undefined ? {
502
- set: props.exitValue
503
- } : undefined,
504
- entryTime: props.entryTime !== undefined ? {
505
- set: props.entryTime
506
- } : undefined,
507
- exitTime: props.exitTime !== undefined ? {
508
- set: props.exitTime
509
- } : undefined,
510
- pnlAmount: props.pnlAmount !== undefined ? {
511
- set: props.pnlAmount
512
- } : undefined,
513
- pnlPercent: props.pnlPercent !== undefined ? {
514
- set: props.pnlPercent
515
- } : undefined,
516
- durationMinutes: props.durationMinutes !== undefined ? {
517
- set: props.durationMinutes
518
- } : undefined,
519
- marketPhase: props.marketPhase !== undefined ? {
520
- set: props.marketPhase
521
- } : undefined,
522
- marketVolatility: props.marketVolatility !== undefined ? {
523
- set: props.marketVolatility
524
- } : undefined,
525
- thresholdsJson: props.thresholdsJson !== undefined ? {
526
- set: props.thresholdsJson
527
- } : undefined,
528
- actions: props.actions ?
529
- Array.isArray(props.actions) && props.actions.length > 0 && props.actions.every((item) => typeof item === 'object' && ('id' in item || 'symbol' in item) && Object.keys(item).length === 1) ? {
530
- connect: props.actions.map((item) => ({
531
- id: item.id
532
- }))
533
- } : { upsert: props.actions.map((item) => ({
534
- where: {
535
- id: item.id !== undefined ? item.id : undefined,
536
- alpacaOrderId: item.alpacaOrderId !== undefined ? item.alpacaOrderId : undefined,
537
- tradeId: item.tradeId !== undefined ? {
538
- equals: item.tradeId
539
- } : undefined,
540
- },
541
- update: {
542
- id: item.id !== undefined ? {
543
- set: item.id
544
- } : undefined,
545
- sequence: item.sequence !== undefined ? {
546
- set: item.sequence
547
- } : undefined,
548
- type: item.type !== undefined ? {
549
- set: item.type
550
- } : undefined,
551
- primary: item.primary !== undefined ? {
552
- set: item.primary
553
- } : undefined,
554
- note: item.note !== undefined ? {
555
- set: item.note
556
- } : undefined,
557
- status: item.status !== undefined ? {
558
- set: item.status
559
- } : undefined,
560
- alpacaOrderId: item.alpacaOrderId !== undefined ? {
561
- set: item.alpacaOrderId
486
+ var _a, _b, _c, _d, _e;
487
+ // Maximum number of retries for database connection issues
488
+ const MAX_RETRIES = 3;
489
+ let retryCount = 0;
490
+ let lastError = null;
491
+ // Retry loop to handle potential database connection issues
492
+ while (retryCount < MAX_RETRIES) {
493
+ try {
494
+ const [modules, client] = await Promise.all([
495
+ (0, client_1.getApolloModules)(),
496
+ globalClient
497
+ ? Promise.resolve(globalClient)
498
+ : client_1.client
499
+ ]);
500
+ const { gql, ApolloError } = modules;
501
+ const UPSERT_ONE_TRADE = gql `
502
+ mutation upsertOneTrade($where: TradeWhereUniqueInput!, $create: TradeCreateInput!, $update: TradeUpdateInput!) {
503
+ upsertOneTrade(where: $where, create: $create, update: $update) {
504
+ ${selectionSet}
505
+ }
506
+ }`;
507
+ const variables = {
508
+ where: {
509
+ id: props.id !== undefined ? props.id : undefined,
510
+ alpacaAccountId: props.alpacaAccountId !== undefined ? {
511
+ equals: props.alpacaAccountId
512
+ } : undefined,
513
+ symbol: props.symbol !== undefined ? {
514
+ equals: props.symbol
515
+ } : undefined,
516
+ },
517
+ create: {
518
+ alpacaAccountId: props.alpacaAccountId !== undefined ? props.alpacaAccountId : undefined,
519
+ signal: props.signal !== undefined ? props.signal : undefined,
520
+ strategy: props.strategy !== undefined ? props.strategy : undefined,
521
+ analysis: props.analysis !== undefined ? props.analysis : undefined,
522
+ summary: props.summary !== undefined ? props.summary : undefined,
523
+ confidence: props.confidence !== undefined ? props.confidence : undefined,
524
+ timestamp: props.timestamp !== undefined ? props.timestamp : undefined,
525
+ status: props.status !== undefined ? props.status : undefined,
526
+ symbol: props.symbol !== undefined ? props.symbol : undefined,
527
+ entryPrice: props.entryPrice !== undefined ? props.entryPrice : undefined,
528
+ exitPrice: props.exitPrice !== undefined ? props.exitPrice : undefined,
529
+ entryQty: props.entryQty !== undefined ? props.entryQty : undefined,
530
+ exitQty: props.exitQty !== undefined ? props.exitQty : undefined,
531
+ entryValue: props.entryValue !== undefined ? props.entryValue : undefined,
532
+ exitValue: props.exitValue !== undefined ? props.exitValue : undefined,
533
+ entryTime: props.entryTime !== undefined ? props.entryTime : undefined,
534
+ exitTime: props.exitTime !== undefined ? props.exitTime : undefined,
535
+ pnlAmount: props.pnlAmount !== undefined ? props.pnlAmount : undefined,
536
+ pnlPercent: props.pnlPercent !== undefined ? props.pnlPercent : undefined,
537
+ durationMinutes: props.durationMinutes !== undefined ? props.durationMinutes : undefined,
538
+ marketPhase: props.marketPhase !== undefined ? props.marketPhase : undefined,
539
+ marketVolatility: props.marketVolatility !== undefined ? props.marketVolatility : undefined,
540
+ thresholdsJson: props.thresholdsJson !== undefined ? props.thresholdsJson : undefined,
541
+ actions: props.actions ?
542
+ Array.isArray(props.actions) && props.actions.length > 0 && props.actions.every((item) => typeof item === 'object' && 'id' in item && Object.keys(item).length === 1) ? {
543
+ connect: props.actions.map((item) => ({
544
+ id: item.id
545
+ }))
546
+ }
547
+ : { connectOrCreate: props.actions.map((item) => ({
548
+ where: {
549
+ id: item.id !== undefined ? item.id : undefined,
550
+ alpacaOrderId: item.alpacaOrderId !== undefined ? item.alpacaOrderId : undefined,
551
+ tradeId: item.tradeId !== undefined ? {
552
+ equals: item.tradeId
553
+ } : undefined,
554
+ },
555
+ create: {
556
+ sequence: item.sequence !== undefined ? item.sequence : undefined,
557
+ type: item.type !== undefined ? item.type : undefined,
558
+ primary: item.primary !== undefined ? item.primary : undefined,
559
+ note: item.note !== undefined ? item.note : undefined,
560
+ status: item.status !== undefined ? item.status : undefined,
561
+ alpacaOrderId: item.alpacaOrderId !== undefined ? item.alpacaOrderId : undefined,
562
+ },
563
+ }))
562
564
  } : undefined,
563
- },
564
- create: {
565
- sequence: item.sequence !== undefined ? item.sequence : undefined,
566
- type: item.type !== undefined ? item.type : undefined,
567
- primary: item.primary !== undefined ? item.primary : undefined,
568
- note: item.note !== undefined ? item.note : undefined,
569
- status: item.status !== undefined ? item.status : undefined,
570
- alpacaOrderId: item.alpacaOrderId !== undefined ? item.alpacaOrderId : undefined,
571
- },
572
- }))
573
- } : undefined,
574
- },
575
- };
576
- const filteredVariables = (0, utils_1.removeUndefinedProps)(variables);
577
- try {
578
- const response = await client.mutate({ mutation: UPSERT_ONE_TRADE, variables: filteredVariables });
579
- if (response.errors && response.errors.length > 0)
580
- throw new Error(response.errors[0].message);
581
- if (response && response.data && response.data.upsertOneTrade) {
582
- return response.data.upsertOneTrade;
565
+ },
566
+ update: {
567
+ alpacaAccountId: props.alpacaAccountId !== undefined ? {
568
+ set: props.alpacaAccountId
569
+ } : undefined,
570
+ signal: props.signal !== undefined ? {
571
+ set: props.signal
572
+ } : undefined,
573
+ strategy: props.strategy !== undefined ? {
574
+ set: props.strategy
575
+ } : undefined,
576
+ analysis: props.analysis !== undefined ? {
577
+ set: props.analysis
578
+ } : undefined,
579
+ summary: props.summary !== undefined ? {
580
+ set: props.summary
581
+ } : undefined,
582
+ confidence: props.confidence !== undefined ? {
583
+ set: props.confidence
584
+ } : undefined,
585
+ timestamp: props.timestamp !== undefined ? {
586
+ set: props.timestamp
587
+ } : undefined,
588
+ status: props.status !== undefined ? {
589
+ set: props.status
590
+ } : undefined,
591
+ symbol: props.symbol !== undefined ? {
592
+ set: props.symbol
593
+ } : undefined,
594
+ entryPrice: props.entryPrice !== undefined ? {
595
+ set: props.entryPrice
596
+ } : undefined,
597
+ exitPrice: props.exitPrice !== undefined ? {
598
+ set: props.exitPrice
599
+ } : undefined,
600
+ entryQty: props.entryQty !== undefined ? {
601
+ set: props.entryQty
602
+ } : undefined,
603
+ exitQty: props.exitQty !== undefined ? {
604
+ set: props.exitQty
605
+ } : undefined,
606
+ entryValue: props.entryValue !== undefined ? {
607
+ set: props.entryValue
608
+ } : undefined,
609
+ exitValue: props.exitValue !== undefined ? {
610
+ set: props.exitValue
611
+ } : undefined,
612
+ entryTime: props.entryTime !== undefined ? {
613
+ set: props.entryTime
614
+ } : undefined,
615
+ exitTime: props.exitTime !== undefined ? {
616
+ set: props.exitTime
617
+ } : undefined,
618
+ pnlAmount: props.pnlAmount !== undefined ? {
619
+ set: props.pnlAmount
620
+ } : undefined,
621
+ pnlPercent: props.pnlPercent !== undefined ? {
622
+ set: props.pnlPercent
623
+ } : undefined,
624
+ durationMinutes: props.durationMinutes !== undefined ? {
625
+ set: props.durationMinutes
626
+ } : undefined,
627
+ marketPhase: props.marketPhase !== undefined ? {
628
+ set: props.marketPhase
629
+ } : undefined,
630
+ marketVolatility: props.marketVolatility !== undefined ? {
631
+ set: props.marketVolatility
632
+ } : undefined,
633
+ thresholdsJson: props.thresholdsJson !== undefined ? {
634
+ set: props.thresholdsJson
635
+ } : undefined,
636
+ actions: props.actions ?
637
+ Array.isArray(props.actions) && props.actions.length > 0 && props.actions.every((item) => typeof item === 'object' && ('id' in item || 'symbol' in item) && Object.keys(item).length === 1) ? {
638
+ connect: props.actions.map((item) => ({
639
+ id: item.id
640
+ }))
641
+ } : { upsert: props.actions.map((item) => ({
642
+ where: {
643
+ id: item.id !== undefined ? item.id : undefined,
644
+ alpacaOrderId: item.alpacaOrderId !== undefined ? item.alpacaOrderId : undefined,
645
+ tradeId: item.tradeId !== undefined ? {
646
+ equals: item.tradeId
647
+ } : undefined,
648
+ },
649
+ update: {
650
+ id: item.id !== undefined ? {
651
+ set: item.id
652
+ } : undefined,
653
+ sequence: item.sequence !== undefined ? {
654
+ set: item.sequence
655
+ } : undefined,
656
+ type: item.type !== undefined ? {
657
+ set: item.type
658
+ } : undefined,
659
+ primary: item.primary !== undefined ? {
660
+ set: item.primary
661
+ } : undefined,
662
+ note: item.note !== undefined ? {
663
+ set: item.note
664
+ } : undefined,
665
+ status: item.status !== undefined ? {
666
+ set: item.status
667
+ } : undefined,
668
+ alpacaOrderId: item.alpacaOrderId !== undefined ? {
669
+ set: item.alpacaOrderId
670
+ } : undefined,
671
+ },
672
+ create: {
673
+ sequence: item.sequence !== undefined ? item.sequence : undefined,
674
+ type: item.type !== undefined ? item.type : undefined,
675
+ primary: item.primary !== undefined ? item.primary : undefined,
676
+ note: item.note !== undefined ? item.note : undefined,
677
+ status: item.status !== undefined ? item.status : undefined,
678
+ alpacaOrderId: item.alpacaOrderId !== undefined ? item.alpacaOrderId : undefined,
679
+ },
680
+ }))
681
+ } : undefined,
682
+ },
683
+ };
684
+ const filteredVariables = (0, utils_1.removeUndefinedProps)(variables);
685
+ const response = await client.mutate({
686
+ mutation: UPSERT_ONE_TRADE,
687
+ variables: filteredVariables,
688
+ // Don't cache mutations, but ensure we're using the freshest context
689
+ fetchPolicy: 'no-cache'
690
+ });
691
+ if (response.errors && response.errors.length > 0)
692
+ throw new Error(response.errors[0].message);
693
+ if (response && response.data && response.data.upsertOneTrade) {
694
+ return response.data.upsertOneTrade;
695
+ }
696
+ else {
697
+ return null;
698
+ }
583
699
  }
584
- else {
585
- return null;
700
+ catch (error) {
701
+ lastError = error;
702
+ // Check if this is a database connection error that we should retry
703
+ const isConnectionError = ((_a = error.message) === null || _a === void 0 ? void 0 : _a.includes('Server has closed the connection')) ||
704
+ ((_b = error.message) === null || _b === void 0 ? void 0 : _b.includes('Cannot reach database server')) ||
705
+ ((_c = error.message) === null || _c === void 0 ? void 0 : _c.includes('Connection timed out')) ||
706
+ ((_d = error.message) === null || _d === void 0 ? void 0 : _d.includes('Accelerate')) || // Prisma Accelerate proxy errors
707
+ (error.networkError && ((_e = error.networkError.message) === null || _e === void 0 ? void 0 : _e.includes('Failed to fetch')));
708
+ if (isConnectionError && retryCount < MAX_RETRIES - 1) {
709
+ retryCount++;
710
+ const delay = Math.pow(2, retryCount) * 100; // Exponential backoff: 200ms, 400ms, 800ms
711
+ console.warn("Database connection error, retrying...");
712
+ await new Promise(resolve => setTimeout(resolve, delay));
713
+ continue;
714
+ }
715
+ // Log the error and rethrow
716
+ console.error("Database error occurred:", error);
717
+ throw error;
586
718
  }
587
719
  }
588
- catch (error) {
589
- console.error('Error in upsertOneTrade:', error);
590
- throw error;
591
- }
720
+ // If we exhausted retries, throw the last error
721
+ throw lastError;
592
722
  },
593
723
  /**
594
724
  * Update multiple Trade records.
725
+ * Enhanced with connection resilience against Prisma connection errors.
595
726
  * @param props - Array of Trade objects for the updated records.
596
727
  * @param globalClient - Apollo Client instance.
597
728
  * @returns The count of created records or null.
598
729
  */
599
730
  async updateMany(props, globalClient) {
600
- const [modules, client] = await Promise.all([
601
- (0, client_1.getApolloModules)(),
602
- globalClient
603
- ? Promise.resolve(globalClient)
604
- : client_1.client
605
- ]);
606
- const { gql, ApolloError } = modules;
607
- const UPDATE_MANY_TRADE = gql `
608
- mutation updateManyTrade($data: [TradeCreateManyInput!]!) {
609
- updateManyTrade(data: $data) {
610
- count
611
- }
612
- }`;
613
- const variables = props.map(prop => ({
614
- where: {
615
- id: prop.id !== undefined ? prop.id : undefined,
616
- alpacaAccountId: prop.alpacaAccountId !== undefined ? {
617
- equals: prop.alpacaAccountId
618
- } : undefined,
619
- symbol: prop.symbol !== undefined ? {
620
- equals: prop.symbol
621
- } : undefined,
622
- },
623
- data: {
624
- id: prop.id !== undefined ? {
625
- set: prop.id
626
- } : undefined,
627
- alpacaAccountId: prop.alpacaAccountId !== undefined ? {
628
- set: prop.alpacaAccountId
629
- } : undefined,
630
- signal: prop.signal !== undefined ? {
631
- set: prop.signal
632
- } : undefined,
633
- strategy: prop.strategy !== undefined ? {
634
- set: prop.strategy
635
- } : undefined,
636
- analysis: prop.analysis !== undefined ? {
637
- set: prop.analysis
638
- } : undefined,
639
- summary: prop.summary !== undefined ? {
640
- set: prop.summary
641
- } : undefined,
642
- confidence: prop.confidence !== undefined ? {
643
- set: prop.confidence
644
- } : undefined,
645
- timestamp: prop.timestamp !== undefined ? {
646
- set: prop.timestamp
647
- } : undefined,
648
- createdAt: prop.createdAt !== undefined ? {
649
- set: prop.createdAt
650
- } : undefined,
651
- updatedAt: prop.updatedAt !== undefined ? {
652
- set: prop.updatedAt
653
- } : undefined,
654
- status: prop.status !== undefined ? {
655
- set: prop.status
656
- } : undefined,
657
- symbol: prop.symbol !== undefined ? {
658
- set: prop.symbol
659
- } : undefined,
660
- entryPrice: prop.entryPrice !== undefined ? {
661
- set: prop.entryPrice
662
- } : undefined,
663
- exitPrice: prop.exitPrice !== undefined ? {
664
- set: prop.exitPrice
665
- } : undefined,
666
- entryQty: prop.entryQty !== undefined ? {
667
- set: prop.entryQty
668
- } : undefined,
669
- exitQty: prop.exitQty !== undefined ? {
670
- set: prop.exitQty
671
- } : undefined,
672
- entryValue: prop.entryValue !== undefined ? {
673
- set: prop.entryValue
674
- } : undefined,
675
- exitValue: prop.exitValue !== undefined ? {
676
- set: prop.exitValue
677
- } : undefined,
678
- entryTime: prop.entryTime !== undefined ? {
679
- set: prop.entryTime
680
- } : undefined,
681
- exitTime: prop.exitTime !== undefined ? {
682
- set: prop.exitTime
683
- } : undefined,
684
- pnlAmount: prop.pnlAmount !== undefined ? {
685
- set: prop.pnlAmount
686
- } : undefined,
687
- pnlPercent: prop.pnlPercent !== undefined ? {
688
- set: prop.pnlPercent
689
- } : undefined,
690
- durationMinutes: prop.durationMinutes !== undefined ? {
691
- set: prop.durationMinutes
692
- } : undefined,
693
- marketPhase: prop.marketPhase !== undefined ? {
694
- set: prop.marketPhase
695
- } : undefined,
696
- marketVolatility: prop.marketVolatility !== undefined ? {
697
- set: prop.marketVolatility
698
- } : undefined,
699
- thresholdsJson: prop.thresholdsJson !== undefined ? {
700
- set: prop.thresholdsJson
701
- } : undefined,
702
- actions: prop.actions ?
703
- Array.isArray(prop.actions) && prop.actions.length > 0 && prop.actions.every((item) => typeof item === 'object' && ('id' in item || 'symbol' in item) && Object.keys(item).length === 1) ? {
704
- connect: prop.actions.map((item) => ({
705
- id: item.id
706
- }))
707
- } : { upsert: prop.actions.map((item) => ({
708
- where: {
709
- id: item.id !== undefined ? item.id : undefined,
710
- alpacaOrderId: item.alpacaOrderId !== undefined ? item.alpacaOrderId : undefined,
711
- tradeId: item.tradeId !== undefined ? {
712
- equals: item.tradeId
713
- } : undefined,
714
- },
715
- update: {
716
- id: item.id !== undefined ? {
717
- set: item.id
718
- } : undefined,
719
- sequence: item.sequence !== undefined ? {
720
- set: item.sequence
721
- } : undefined,
722
- type: item.type !== undefined ? {
723
- set: item.type
724
- } : undefined,
725
- primary: item.primary !== undefined ? {
726
- set: item.primary
727
- } : undefined,
728
- note: item.note !== undefined ? {
729
- set: item.note
730
- } : undefined,
731
- status: item.status !== undefined ? {
732
- set: item.status
733
- } : undefined,
734
- alpacaOrderId: item.alpacaOrderId !== undefined ? {
735
- set: item.alpacaOrderId
736
- } : undefined,
737
- },
738
- create: {
739
- sequence: item.sequence !== undefined ? item.sequence : undefined,
740
- type: item.type !== undefined ? item.type : undefined,
741
- primary: item.primary !== undefined ? item.primary : undefined,
742
- note: item.note !== undefined ? item.note : undefined,
743
- status: item.status !== undefined ? item.status : undefined,
744
- alpacaOrderId: item.alpacaOrderId !== undefined ? item.alpacaOrderId : undefined,
745
- },
746
- }))
747
- } : undefined,
748
- },
749
- }));
750
- const filteredVariables = (0, utils_1.removeUndefinedProps)(variables);
751
- try {
752
- const response = await client.mutate({ mutation: UPDATE_MANY_TRADE, variables: filteredVariables });
753
- if (response.errors && response.errors.length > 0)
754
- throw new Error(response.errors[0].message);
755
- if (response && response.data && response.data.updateManyTrade) {
756
- return response.data.updateManyTrade;
731
+ var _a, _b, _c, _d, _e;
732
+ // Maximum number of retries for database connection issues
733
+ const MAX_RETRIES = 3;
734
+ let retryCount = 0;
735
+ let lastError = null;
736
+ // Retry loop to handle potential database connection issues
737
+ while (retryCount < MAX_RETRIES) {
738
+ try {
739
+ const [modules, client] = await Promise.all([
740
+ (0, client_1.getApolloModules)(),
741
+ globalClient
742
+ ? Promise.resolve(globalClient)
743
+ : client_1.client
744
+ ]);
745
+ const { gql, ApolloError } = modules;
746
+ const UPDATE_MANY_TRADE = gql `
747
+ mutation updateManyTrade($data: [TradeCreateManyInput!]!) {
748
+ updateManyTrade(data: $data) {
749
+ count
750
+ }
751
+ }`;
752
+ const variables = props.map(prop => ({
753
+ where: {
754
+ id: prop.id !== undefined ? prop.id : undefined,
755
+ alpacaAccountId: prop.alpacaAccountId !== undefined ? {
756
+ equals: prop.alpacaAccountId
757
+ } : undefined,
758
+ symbol: prop.symbol !== undefined ? {
759
+ equals: prop.symbol
760
+ } : undefined,
761
+ },
762
+ data: {
763
+ id: prop.id !== undefined ? {
764
+ set: prop.id
765
+ } : undefined,
766
+ alpacaAccountId: prop.alpacaAccountId !== undefined ? {
767
+ set: prop.alpacaAccountId
768
+ } : undefined,
769
+ signal: prop.signal !== undefined ? {
770
+ set: prop.signal
771
+ } : undefined,
772
+ strategy: prop.strategy !== undefined ? {
773
+ set: prop.strategy
774
+ } : undefined,
775
+ analysis: prop.analysis !== undefined ? {
776
+ set: prop.analysis
777
+ } : undefined,
778
+ summary: prop.summary !== undefined ? {
779
+ set: prop.summary
780
+ } : undefined,
781
+ confidence: prop.confidence !== undefined ? {
782
+ set: prop.confidence
783
+ } : undefined,
784
+ timestamp: prop.timestamp !== undefined ? {
785
+ set: prop.timestamp
786
+ } : undefined,
787
+ createdAt: prop.createdAt !== undefined ? {
788
+ set: prop.createdAt
789
+ } : undefined,
790
+ updatedAt: prop.updatedAt !== undefined ? {
791
+ set: prop.updatedAt
792
+ } : undefined,
793
+ status: prop.status !== undefined ? {
794
+ set: prop.status
795
+ } : undefined,
796
+ symbol: prop.symbol !== undefined ? {
797
+ set: prop.symbol
798
+ } : undefined,
799
+ entryPrice: prop.entryPrice !== undefined ? {
800
+ set: prop.entryPrice
801
+ } : undefined,
802
+ exitPrice: prop.exitPrice !== undefined ? {
803
+ set: prop.exitPrice
804
+ } : undefined,
805
+ entryQty: prop.entryQty !== undefined ? {
806
+ set: prop.entryQty
807
+ } : undefined,
808
+ exitQty: prop.exitQty !== undefined ? {
809
+ set: prop.exitQty
810
+ } : undefined,
811
+ entryValue: prop.entryValue !== undefined ? {
812
+ set: prop.entryValue
813
+ } : undefined,
814
+ exitValue: prop.exitValue !== undefined ? {
815
+ set: prop.exitValue
816
+ } : undefined,
817
+ entryTime: prop.entryTime !== undefined ? {
818
+ set: prop.entryTime
819
+ } : undefined,
820
+ exitTime: prop.exitTime !== undefined ? {
821
+ set: prop.exitTime
822
+ } : undefined,
823
+ pnlAmount: prop.pnlAmount !== undefined ? {
824
+ set: prop.pnlAmount
825
+ } : undefined,
826
+ pnlPercent: prop.pnlPercent !== undefined ? {
827
+ set: prop.pnlPercent
828
+ } : undefined,
829
+ durationMinutes: prop.durationMinutes !== undefined ? {
830
+ set: prop.durationMinutes
831
+ } : undefined,
832
+ marketPhase: prop.marketPhase !== undefined ? {
833
+ set: prop.marketPhase
834
+ } : undefined,
835
+ marketVolatility: prop.marketVolatility !== undefined ? {
836
+ set: prop.marketVolatility
837
+ } : undefined,
838
+ thresholdsJson: prop.thresholdsJson !== undefined ? {
839
+ set: prop.thresholdsJson
840
+ } : undefined,
841
+ actions: prop.actions ?
842
+ Array.isArray(prop.actions) && prop.actions.length > 0 && prop.actions.every((item) => typeof item === 'object' && ('id' in item || 'symbol' in item) && Object.keys(item).length === 1) ? {
843
+ connect: prop.actions.map((item) => ({
844
+ id: item.id
845
+ }))
846
+ } : { upsert: prop.actions.map((item) => ({
847
+ where: {
848
+ id: item.id !== undefined ? item.id : undefined,
849
+ alpacaOrderId: item.alpacaOrderId !== undefined ? item.alpacaOrderId : undefined,
850
+ tradeId: item.tradeId !== undefined ? {
851
+ equals: item.tradeId
852
+ } : undefined,
853
+ },
854
+ update: {
855
+ id: item.id !== undefined ? {
856
+ set: item.id
857
+ } : undefined,
858
+ sequence: item.sequence !== undefined ? {
859
+ set: item.sequence
860
+ } : undefined,
861
+ type: item.type !== undefined ? {
862
+ set: item.type
863
+ } : undefined,
864
+ primary: item.primary !== undefined ? {
865
+ set: item.primary
866
+ } : undefined,
867
+ note: item.note !== undefined ? {
868
+ set: item.note
869
+ } : undefined,
870
+ status: item.status !== undefined ? {
871
+ set: item.status
872
+ } : undefined,
873
+ alpacaOrderId: item.alpacaOrderId !== undefined ? {
874
+ set: item.alpacaOrderId
875
+ } : undefined,
876
+ },
877
+ create: {
878
+ sequence: item.sequence !== undefined ? item.sequence : undefined,
879
+ type: item.type !== undefined ? item.type : undefined,
880
+ primary: item.primary !== undefined ? item.primary : undefined,
881
+ note: item.note !== undefined ? item.note : undefined,
882
+ status: item.status !== undefined ? item.status : undefined,
883
+ alpacaOrderId: item.alpacaOrderId !== undefined ? item.alpacaOrderId : undefined,
884
+ },
885
+ }))
886
+ } : undefined,
887
+ },
888
+ }));
889
+ const filteredVariables = (0, utils_1.removeUndefinedProps)(variables);
890
+ const response = await client.mutate({
891
+ mutation: UPDATE_MANY_TRADE,
892
+ variables: filteredVariables,
893
+ // Don't cache mutations, but ensure we're using the freshest context
894
+ fetchPolicy: 'no-cache'
895
+ });
896
+ if (response.errors && response.errors.length > 0)
897
+ throw new Error(response.errors[0].message);
898
+ if (response && response.data && response.data.updateManyTrade) {
899
+ return response.data.updateManyTrade;
900
+ }
901
+ else {
902
+ return null;
903
+ }
757
904
  }
758
- else {
759
- return null;
905
+ catch (error) {
906
+ lastError = error;
907
+ // Check if this is a database connection error that we should retry
908
+ const isConnectionError = ((_a = error.message) === null || _a === void 0 ? void 0 : _a.includes('Server has closed the connection')) ||
909
+ ((_b = error.message) === null || _b === void 0 ? void 0 : _b.includes('Cannot reach database server')) ||
910
+ ((_c = error.message) === null || _c === void 0 ? void 0 : _c.includes('Connection timed out')) ||
911
+ ((_d = error.message) === null || _d === void 0 ? void 0 : _d.includes('Accelerate')) || // Prisma Accelerate proxy errors
912
+ (error.networkError && ((_e = error.networkError.message) === null || _e === void 0 ? void 0 : _e.includes('Failed to fetch')));
913
+ if (isConnectionError && retryCount < MAX_RETRIES - 1) {
914
+ retryCount++;
915
+ const delay = Math.pow(2, retryCount) * 100; // Exponential backoff: 200ms, 400ms, 800ms
916
+ console.warn("Database connection error, retrying...");
917
+ await new Promise(resolve => setTimeout(resolve, delay));
918
+ continue;
919
+ }
920
+ // Log the error and rethrow
921
+ console.error("Database error occurred:", error);
922
+ throw error;
760
923
  }
761
924
  }
762
- catch (error) {
763
- console.error('Error in updateManyTrade:', error);
764
- throw error;
765
- }
925
+ // If we exhausted retries, throw the last error
926
+ throw lastError;
766
927
  },
767
928
  /**
768
929
  * Delete a single Trade record.
769
- * @param props - Properties to update.
930
+ * Enhanced with connection resilience against Prisma connection errors.
931
+ * @param props - Properties to identify the record to delete.
770
932
  * @param globalClient - Apollo Client instance.
771
933
  * @returns The deleted Trade or null.
772
934
  */
773
935
  async delete(props, globalClient) {
774
- const [modules, client] = await Promise.all([
775
- (0, client_1.getApolloModules)(),
776
- globalClient
777
- ? Promise.resolve(globalClient)
778
- : client_1.client
779
- ]);
780
- const { gql, ApolloError } = modules;
781
- const DELETE_ONE_TRADE = gql `
782
- mutation deleteOneTrade($where: TradeWhereUniqueInput!) {
783
- deleteOneTrade(where: $where) {
784
- id
785
- }
786
- }`;
787
- const variables = {
788
- where: {
789
- id: props.id ? props.id : undefined,
936
+ var _a, _b, _c, _d, _e;
937
+ // Maximum number of retries for database connection issues
938
+ const MAX_RETRIES = 3;
939
+ let retryCount = 0;
940
+ let lastError = null;
941
+ // Retry loop to handle potential database connection issues
942
+ while (retryCount < MAX_RETRIES) {
943
+ try {
944
+ const [modules, client] = await Promise.all([
945
+ (0, client_1.getApolloModules)(),
946
+ globalClient
947
+ ? Promise.resolve(globalClient)
948
+ : client_1.client
949
+ ]);
950
+ const { gql, ApolloError } = modules;
951
+ const DELETE_ONE_TRADE = gql `
952
+ mutation deleteOneTrade($where: TradeWhereUniqueInput!) {
953
+ deleteOneTrade(where: $where) {
954
+ id
790
955
  }
791
- };
792
- const filteredVariables = (0, utils_1.removeUndefinedProps)(variables);
793
- try {
794
- const response = await client.mutate({ mutation: DELETE_ONE_TRADE, variables: filteredVariables });
795
- if (response.errors && response.errors.length > 0)
796
- throw new Error(response.errors[0].message);
797
- if (response && response.data && response.data.deleteOneTrade) {
798
- return response.data.deleteOneTrade;
956
+ }`;
957
+ const variables = {
958
+ where: {
959
+ id: props.id ? props.id : undefined,
960
+ }
961
+ };
962
+ const filteredVariables = (0, utils_1.removeUndefinedProps)(variables);
963
+ const response = await client.mutate({
964
+ mutation: DELETE_ONE_TRADE,
965
+ variables: filteredVariables,
966
+ // Don't cache mutations, but ensure we're using the freshest context
967
+ fetchPolicy: 'no-cache'
968
+ });
969
+ if (response.errors && response.errors.length > 0)
970
+ throw new Error(response.errors[0].message);
971
+ if (response && response.data && response.data.deleteOneTrade) {
972
+ return response.data.deleteOneTrade;
973
+ }
974
+ else {
975
+ return null;
976
+ }
799
977
  }
800
- else {
801
- return null;
978
+ catch (error) {
979
+ lastError = error;
980
+ // Check if this is a database connection error that we should retry
981
+ const isConnectionError = ((_a = error.message) === null || _a === void 0 ? void 0 : _a.includes('Server has closed the connection')) ||
982
+ ((_b = error.message) === null || _b === void 0 ? void 0 : _b.includes('Cannot reach database server')) ||
983
+ ((_c = error.message) === null || _c === void 0 ? void 0 : _c.includes('Connection timed out')) ||
984
+ ((_d = error.message) === null || _d === void 0 ? void 0 : _d.includes('Accelerate')) || // Prisma Accelerate proxy errors
985
+ (error.networkError && ((_e = error.networkError.message) === null || _e === void 0 ? void 0 : _e.includes('Failed to fetch')));
986
+ if (isConnectionError && retryCount < MAX_RETRIES - 1) {
987
+ retryCount++;
988
+ const delay = Math.pow(2, retryCount) * 100; // Exponential backoff: 200ms, 400ms, 800ms
989
+ console.warn("Database connection error, retrying...");
990
+ await new Promise(resolve => setTimeout(resolve, delay));
991
+ continue;
992
+ }
993
+ // Log the error and rethrow
994
+ console.error("Database error occurred:", error);
995
+ throw error;
802
996
  }
803
997
  }
804
- catch (error) {
805
- console.error('Error in deleteOneTrade:', error);
806
- throw error;
807
- }
998
+ // If we exhausted retries, throw the last error
999
+ throw lastError;
808
1000
  },
809
1001
  /**
810
1002
  * Retrieve a single Trade record by ID.
811
- * @param props - Properties to update.
1003
+ * Enhanced with connection resilience against Prisma connection errors.
1004
+ * @param props - Properties to identify the record.
812
1005
  * @param globalClient - Apollo Client instance.
1006
+ * @param whereInput - Optional custom where input.
813
1007
  * @returns The retrieved Trade or null.
814
1008
  */
815
1009
  async get(props, globalClient, whereInput) {
816
- var _a, _b;
817
- const [modules, client] = await Promise.all([
818
- (0, client_1.getApolloModules)(),
819
- globalClient
820
- ? Promise.resolve(globalClient)
821
- : client_1.client
822
- ]);
823
- const { gql, ApolloError } = modules;
824
- const GET_TRADE = gql `
825
- query getTrade($where: TradeWhereUniqueInput!) {
826
- getTrade(where: $where) {
827
- ${selectionSet}
828
- }
829
- }`;
830
- const variables = {
831
- where: whereInput ? whereInput : {
832
- id: props.id !== undefined ? props.id : undefined,
833
- alpacaAccountId: props.alpacaAccountId !== undefined ? {
834
- equals: props.alpacaAccountId
835
- } : undefined,
836
- symbol: props.symbol !== undefined ? {
837
- equals: props.symbol
838
- } : undefined,
839
- },
840
- };
841
- const filteredVariables = (0, utils_1.removeUndefinedProps)(variables);
842
- try {
843
- const response = await client.query({ query: GET_TRADE, variables: filteredVariables });
844
- if (response.errors && response.errors.length > 0)
845
- throw new Error(response.errors[0].message);
846
- return (_b = (_a = response.data) === null || _a === void 0 ? void 0 : _a.getTrade) !== null && _b !== void 0 ? _b : null;
847
- }
848
- catch (error) {
849
- if (error instanceof ApolloError && error.message === 'No Trade found') {
850
- return null;
1010
+ var _a, _b, _c, _d, _e, _f, _g;
1011
+ // Maximum number of retries for database connection issues
1012
+ const MAX_RETRIES = 3;
1013
+ let retryCount = 0;
1014
+ let lastError = null;
1015
+ // Retry loop to handle potential database connection issues
1016
+ while (retryCount < MAX_RETRIES) {
1017
+ try {
1018
+ const [modules, client] = await Promise.all([
1019
+ (0, client_1.getApolloModules)(),
1020
+ globalClient
1021
+ ? Promise.resolve(globalClient)
1022
+ : client_1.client
1023
+ ]);
1024
+ const { gql, ApolloError } = modules;
1025
+ const GET_TRADE = gql `
1026
+ query getTrade($where: TradeWhereUniqueInput!) {
1027
+ getTrade(where: $where) {
1028
+ ${selectionSet}
1029
+ }
1030
+ }`;
1031
+ const variables = {
1032
+ where: whereInput ? whereInput : {
1033
+ id: props.id !== undefined ? props.id : undefined,
1034
+ alpacaAccountId: props.alpacaAccountId !== undefined ? {
1035
+ equals: props.alpacaAccountId
1036
+ } : undefined,
1037
+ symbol: props.symbol !== undefined ? {
1038
+ equals: props.symbol
1039
+ } : undefined,
1040
+ },
1041
+ };
1042
+ const filteredVariables = (0, utils_1.removeUndefinedProps)(variables);
1043
+ const response = await client.query({
1044
+ query: GET_TRADE,
1045
+ variables: filteredVariables,
1046
+ fetchPolicy: 'network-only', // Force network request to avoid stale cache
1047
+ });
1048
+ if (response.errors && response.errors.length > 0)
1049
+ throw new Error(response.errors[0].message);
1050
+ return (_b = (_a = response.data) === null || _a === void 0 ? void 0 : _a.getTrade) !== null && _b !== void 0 ? _b : null;
851
1051
  }
852
- else {
853
- console.error('Error in getTrade:', error);
1052
+ catch (error) {
1053
+ lastError = error;
1054
+ // Check if this is a "No record found" error - this is an expected condition, not a failure
1055
+ if (error.message === 'No Trade found') {
1056
+ return null;
1057
+ }
1058
+ // Check if this is a database connection error that we should retry
1059
+ const isConnectionError = ((_c = error.message) === null || _c === void 0 ? void 0 : _c.includes('Server has closed the connection')) ||
1060
+ ((_d = error.message) === null || _d === void 0 ? void 0 : _d.includes('Cannot reach database server')) ||
1061
+ ((_e = error.message) === null || _e === void 0 ? void 0 : _e.includes('Connection timed out')) ||
1062
+ ((_f = error.message) === null || _f === void 0 ? void 0 : _f.includes('Accelerate')) || // Prisma Accelerate proxy errors
1063
+ (error.networkError && ((_g = error.networkError.message) === null || _g === void 0 ? void 0 : _g.includes('Failed to fetch')));
1064
+ if (isConnectionError && retryCount < MAX_RETRIES - 1) {
1065
+ retryCount++;
1066
+ const delay = Math.pow(2, retryCount) * 100; // Exponential backoff: 200ms, 400ms, 800ms
1067
+ console.warn("Database connection error, retrying...");
1068
+ await new Promise(resolve => setTimeout(resolve, delay));
1069
+ continue;
1070
+ }
1071
+ // Log the error and rethrow
1072
+ console.error("Database error occurred:", error);
854
1073
  throw error;
855
1074
  }
856
1075
  }
1076
+ // If we exhausted retries, throw the last error
1077
+ throw lastError;
857
1078
  },
858
1079
  /**
859
1080
  * Retrieve all Trades records.
1081
+ * Enhanced with connection resilience against Prisma connection errors.
860
1082
  * @param globalClient - Apollo Client instance.
861
1083
  * @returns An array of Trade records or null.
862
1084
  */
863
1085
  async getAll(globalClient) {
864
- var _a, _b;
865
- const [modules, client] = await Promise.all([
866
- (0, client_1.getApolloModules)(),
867
- globalClient
868
- ? Promise.resolve(globalClient)
869
- : client_1.client
870
- ]);
871
- const { gql, ApolloError } = modules;
872
- const GET_ALL_TRADE = gql `
873
- query getAllTrade {
874
- trades {
875
- ${selectionSet}
876
- }
877
- }`;
878
- try {
879
- const response = await client.query({ query: GET_ALL_TRADE });
880
- if (response.errors && response.errors.length > 0)
881
- throw new Error(response.errors[0].message);
882
- return (_b = (_a = response.data) === null || _a === void 0 ? void 0 : _a.trades) !== null && _b !== void 0 ? _b : null;
883
- }
884
- catch (error) {
885
- if (error instanceof ApolloError && error.message === 'No Trade found') {
886
- return null;
1086
+ var _a, _b, _c, _d, _e, _f, _g;
1087
+ // Maximum number of retries for database connection issues
1088
+ const MAX_RETRIES = 3;
1089
+ let retryCount = 0;
1090
+ let lastError = null;
1091
+ // Retry loop to handle potential database connection issues
1092
+ while (retryCount < MAX_RETRIES) {
1093
+ try {
1094
+ const [modules, client] = await Promise.all([
1095
+ (0, client_1.getApolloModules)(),
1096
+ globalClient
1097
+ ? Promise.resolve(globalClient)
1098
+ : client_1.client
1099
+ ]);
1100
+ const { gql, ApolloError } = modules;
1101
+ const GET_ALL_TRADE = gql `
1102
+ query getAllTrade {
1103
+ trades {
1104
+ ${selectionSet}
1105
+ }
1106
+ }`;
1107
+ const response = await client.query({
1108
+ query: GET_ALL_TRADE,
1109
+ fetchPolicy: 'network-only', // Force network request to avoid stale cache
1110
+ });
1111
+ if (response.errors && response.errors.length > 0)
1112
+ throw new Error(response.errors[0].message);
1113
+ return (_b = (_a = response.data) === null || _a === void 0 ? void 0 : _a.trades) !== null && _b !== void 0 ? _b : null;
887
1114
  }
888
- else {
889
- console.error('Error in getTrade:', error);
1115
+ catch (error) {
1116
+ lastError = error;
1117
+ // Check if this is a "No record found" error - this is an expected condition, not a failure
1118
+ if (error.message === 'No Trade found') {
1119
+ return null;
1120
+ }
1121
+ // Check if this is a database connection error that we should retry
1122
+ const isConnectionError = ((_c = error.message) === null || _c === void 0 ? void 0 : _c.includes('Server has closed the connection')) ||
1123
+ ((_d = error.message) === null || _d === void 0 ? void 0 : _d.includes('Cannot reach database server')) ||
1124
+ ((_e = error.message) === null || _e === void 0 ? void 0 : _e.includes('Connection timed out')) ||
1125
+ ((_f = error.message) === null || _f === void 0 ? void 0 : _f.includes('Accelerate')) || // Prisma Accelerate proxy errors
1126
+ (error.networkError && ((_g = error.networkError.message) === null || _g === void 0 ? void 0 : _g.includes('Failed to fetch')));
1127
+ if (isConnectionError && retryCount < MAX_RETRIES - 1) {
1128
+ retryCount++;
1129
+ const delay = Math.pow(2, retryCount) * 100; // Exponential backoff: 200ms, 400ms, 800ms
1130
+ console.warn("Database connection error, retrying...");
1131
+ await new Promise(resolve => setTimeout(resolve, delay));
1132
+ continue;
1133
+ }
1134
+ // Log the error and rethrow
1135
+ console.error("Database error occurred:", error);
890
1136
  throw error;
891
1137
  }
892
1138
  }
1139
+ // If we exhausted retries, throw the last error
1140
+ throw lastError;
893
1141
  },
894
1142
  /**
895
1143
  * Find multiple Trade records based on conditions.
1144
+ * Enhanced with connection resilience against Prisma connection errors.
896
1145
  * @param props - Conditions to find records.
897
1146
  * @param globalClient - Apollo Client instance.
1147
+ * @param whereInput - Optional custom where input.
898
1148
  * @returns An array of found Trade records or null.
899
1149
  */
900
1150
  async findMany(props, globalClient, whereInput) {
901
- const [modules, client] = await Promise.all([
902
- (0, client_1.getApolloModules)(),
903
- globalClient
904
- ? Promise.resolve(globalClient)
905
- : client_1.client
906
- ]);
907
- const { gql, ApolloError } = modules;
908
- const FIND_MANY_TRADE = gql `
909
- query findManyTrade($where: TradeWhereInput!) {
910
- trades(where: $where) {
911
- ${selectionSet}
912
- }
913
- }`;
914
- const variables = {
915
- where: whereInput ? whereInput : {
916
- id: props.id !== undefined ? {
917
- equals: props.id
918
- } : undefined,
919
- alpacaAccountId: props.alpacaAccountId !== undefined ? {
920
- equals: props.alpacaAccountId
921
- } : undefined,
922
- symbol: props.symbol !== undefined ? {
923
- equals: props.symbol
924
- } : undefined,
925
- },
926
- };
927
- const filteredVariables = (0, utils_1.removeUndefinedProps)(variables);
928
- try {
929
- const response = await client.query({ query: FIND_MANY_TRADE, variables: filteredVariables });
930
- if (response.errors && response.errors.length > 0)
931
- throw new Error(response.errors[0].message);
932
- if (response && response.data && response.data.trades) {
933
- return response.data.trades;
934
- }
935
- else {
936
- return [];
1151
+ var _a, _b, _c, _d, _e;
1152
+ // Maximum number of retries for database connection issues
1153
+ const MAX_RETRIES = 3;
1154
+ let retryCount = 0;
1155
+ let lastError = null;
1156
+ // Retry loop to handle potential database connection issues
1157
+ while (retryCount < MAX_RETRIES) {
1158
+ try {
1159
+ const [modules, client] = await Promise.all([
1160
+ (0, client_1.getApolloModules)(),
1161
+ globalClient
1162
+ ? Promise.resolve(globalClient)
1163
+ : client_1.client
1164
+ ]);
1165
+ const { gql, ApolloError } = modules;
1166
+ const FIND_MANY_TRADE = gql `
1167
+ query findManyTrade($where: TradeWhereInput!) {
1168
+ trades(where: $where) {
1169
+ ${selectionSet}
937
1170
  }
938
- }
939
- catch (error) {
940
- if (error instanceof ApolloError && error.message === 'No Trade found') {
941
- return null;
1171
+ }`;
1172
+ const variables = {
1173
+ where: whereInput ? whereInput : {
1174
+ id: props.id !== undefined ? {
1175
+ equals: props.id
1176
+ } : undefined,
1177
+ alpacaAccountId: props.alpacaAccountId !== undefined ? {
1178
+ equals: props.alpacaAccountId
1179
+ } : undefined,
1180
+ symbol: props.symbol !== undefined ? {
1181
+ equals: props.symbol
1182
+ } : undefined,
1183
+ },
1184
+ };
1185
+ const filteredVariables = (0, utils_1.removeUndefinedProps)(variables);
1186
+ const response = await client.query({
1187
+ query: FIND_MANY_TRADE,
1188
+ variables: filteredVariables,
1189
+ fetchPolicy: 'network-only', // Force network request to avoid stale cache
1190
+ });
1191
+ if (response.errors && response.errors.length > 0)
1192
+ throw new Error(response.errors[0].message);
1193
+ if (response && response.data && response.data.trades) {
1194
+ return response.data.trades;
1195
+ }
1196
+ else {
1197
+ return [];
1198
+ }
942
1199
  }
943
- else {
944
- console.error('Error in getTrade:', error);
1200
+ catch (error) {
1201
+ lastError = error;
1202
+ // Check if this is a "No record found" error - this is an expected condition, not a failure
1203
+ if (error.message === 'No Trade found') {
1204
+ return null;
1205
+ }
1206
+ // Check if this is a database connection error that we should retry
1207
+ const isConnectionError = ((_a = error.message) === null || _a === void 0 ? void 0 : _a.includes('Server has closed the connection')) ||
1208
+ ((_b = error.message) === null || _b === void 0 ? void 0 : _b.includes('Cannot reach database server')) ||
1209
+ ((_c = error.message) === null || _c === void 0 ? void 0 : _c.includes('Connection timed out')) ||
1210
+ ((_d = error.message) === null || _d === void 0 ? void 0 : _d.includes('Accelerate')) || // Prisma Accelerate proxy errors
1211
+ (error.networkError && ((_e = error.networkError.message) === null || _e === void 0 ? void 0 : _e.includes('Failed to fetch')));
1212
+ if (isConnectionError && retryCount < MAX_RETRIES - 1) {
1213
+ retryCount++;
1214
+ const delay = Math.pow(2, retryCount) * 100; // Exponential backoff: 200ms, 400ms, 800ms
1215
+ console.warn("Database connection error, retrying...");
1216
+ await new Promise(resolve => setTimeout(resolve, delay));
1217
+ continue;
1218
+ }
1219
+ // Log the error and rethrow
1220
+ console.error("Database error occurred:", error);
945
1221
  throw error;
946
1222
  }
947
1223
  }
1224
+ // If we exhausted retries, throw the last error
1225
+ throw lastError;
948
1226
  }
949
1227
  };
950
1228
  //# sourceMappingURL=Trade.js.map