bulltrackers-module 1.0.123 → 1.0.124

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.
@@ -1,3 +1,8 @@
1
+ /*
2
+ * FILENAME: CloudFunctions/NpmWrappers/bulltrackers-module/functions/orchestrator/helpers/discovery_helpers.js
3
+ * (FIXED: Publishes 'discover' tasks in the correct batch format { tasks: [...] })
4
+ */
5
+
1
6
  /**
2
7
  * @fileoverview Orchestrator's discovery sub-pipes.
3
8
  * REFACTORED: All functions are now stateless and receive dependencies.
@@ -164,11 +169,11 @@ async function getDiscoveryCandidates(userType, blocksToFill, config, dependenci
164
169
  * @returns {Promise<void>}
165
170
  */
166
171
  async function dispatchDiscovery(userType, candidates, config, dependencies) {
167
- const { logger, firestoreUtils, pubsubUtils } = dependencies;
172
+ const { logger, firestoreUtils, pubsubUtils, pubsub } = dependencies; // <-- Add pubsub
168
173
  const {
169
174
  topicName,
170
175
  dispatchBatchSize,
171
- pubsubBatchSize,
176
+ pubsubBatchSize, // This is no longer used by this function
172
177
  pendingSpecCollection,
173
178
  pendingMaxFieldsPerDoc,
174
179
  pendingMaxWritesPerBatch
@@ -208,14 +213,43 @@ async function dispatchDiscovery(userType, candidates, config, dependencies) {
208
213
  }
209
214
  }
210
215
 
211
- // Pass dependencies and config to core util
212
- await pubsubUtils.batchPublishTasks(dependencies, {
213
- topicName,
214
- tasks,
215
- taskType: `${userType} discovery`,
216
- maxPubsubBatchSize: pubsubBatchSize
217
- });
218
- logger.log('SUCCESS', `[Orchestrator Helpers] Dispatched ${tasks.length} task messages (${candidates.size} CIDs) for ${userType} discovery.`);
216
+ // --- START FIX: RE-IMPLEMENT BATCHING LOGIC ---
217
+ const topic = pubsub.topic(topicName);
218
+ let totalCidsPublished = 0;
219
+ let messagesPublished = 0;
220
+
221
+ // 'tasks' is an array of 'discover' task objects. We group them into
222
+ // batches and publish each batch as a single message.
223
+ // We use `dispatchBatchSize` here to determine how many 'discover' tasks go into one message.
224
+ // This value should probably be small, like 1-10.
225
+
226
+ // Let's re-use `dispatchBatchSize` as the number of *tasks* per message.
227
+ // If `tasks.length` is 200 and `dispatchBatchSize` is 50, this will create 4 messages.
228
+ // This seems correct.
229
+
230
+ for (let i = 0; i < tasks.length; i += dispatchBatchSize) {
231
+ // This batch contains multiple 'discover' tasks
232
+ const batchOfTasks = tasks.slice(i, i + dispatchBatchSize);
233
+
234
+ // Wrap this batch in the new payload format
235
+ const messagePayload = { tasks: batchOfTasks };
236
+
237
+ try {
238
+ await topic.publishMessage({ json: messagePayload });
239
+
240
+ // Log the number of CIDs in this message
241
+ const cidsInThisMessage = batchOfTasks.reduce((acc, task) => acc + task.cids.length, 0);
242
+ totalCidsPublished += cidsInThisMessage;
243
+ messagesPublished++;
244
+
245
+ logger.log('INFO', `[Orchestrator Helpers] Dispatched batch ${messagesPublished} with ${batchOfTasks.length} discover tasks (${cidsInThisMessage} CIDs) as 1 Pub/Sub message.`);
246
+ } catch (publishError) {
247
+ logger.log('ERROR', `[Orchestrator Helpers] Failed to publish discover batch ${messagesPublished + 1}.`, { error: publishError.message });
248
+ }
249
+ }
250
+
251
+ logger.log('SUCCESS', `[Orchestrator Helpers] Dispatched ${totalCidsPublished} CIDs in ${tasks.length} tasks, grouped into ${messagesPublished} Pub/Sub messages for ${userType} discovery.`);
252
+ // --- END FIX ---
219
253
  }
220
254
 
221
255
 
@@ -223,4 +257,4 @@ module.exports = {
223
257
  checkDiscoveryNeed,
224
258
  getDiscoveryCandidates,
225
259
  dispatchDiscovery,
226
- };
260
+ };
@@ -1,3 +1,8 @@
1
+ /*
2
+ * FILENAME: CloudFunctions/NpmWrappers/bulltrackers-module/functions/task-engine/helpers/discover_helpers.js
3
+ * (FIXED: Publishes 'verify' task in the correct batch format { tasks: [...] })
4
+ */
5
+
1
6
  /**
2
7
  * @fileoverview Sub-pipe: pipe.taskEngine.handleDiscover
3
8
  * REFACTORED: Now stateless and receives dependencies.
@@ -119,10 +124,12 @@ async function handleDiscover(task, taskId, dependencies, config) {
119
124
  };
120
125
  // --- END MODIFICATION ---
121
126
 
127
+ // --- FIX: WRAP IN BATCH FORMAT ---
122
128
  // Use pubsub from dependencies
123
129
  await pubsub.topic(config.PUBSUB_TOPIC_USER_FETCH)
124
- .publishMessage({ json: verificationTask });
125
- logger.log('INFO', `[DISCOVER] Verification message published was : ${JSON.stringify(verificationTask)} `);
130
+ .publishMessage({ json: { tasks: [verificationTask] } });
131
+ logger.log('INFO', `[DISCOVER] Verification message published was : ${JSON.stringify({ tasks: [verificationTask] })} `);
132
+ // --- END FIX ---
126
133
  logger.log('INFO', `[DISCOVER] Chaining to 'verify' task for ${finalActiveUsers.length} active users.`);
127
134
  }
128
135
 
@@ -1,3 +1,8 @@
1
+ /*
2
+ * FILENAME: CloudFunctions/NpmWrappers/bulltrackers-module/functions/task-engine/helpers/update_helpers.js
3
+ * (FIXED: Enhanced error logging for portfolio and history fetches)
4
+ */
5
+
1
6
  /**
2
7
  * @fileoverview Sub-pipe: pipe.taskEngine.handleUpdate
3
8
  * REFACTORED: Now stateless and receives dependencies.
@@ -122,12 +127,30 @@ async function handleUpdate(task, taskId, dependencies, config, username) {
122
127
  wasPortfolioSuccess = true;
123
128
  const portfolioData = JSON.parse(responseBody);
124
129
  // Add to portfolio batch
130
+ console.log('DEBUG', `[UPDATE] SUCCESS Adding portfolio data for user ${userId} to batch.`);
125
131
  await batchManager.addToPortfolioBatch(userId, portfolioStorageBlockId, today, portfolioData, userType, instrumentId);
132
+
126
133
  }
127
134
  } else {
128
- // Log failure
129
- const errorMsg = portfolioResult.status === 'rejected' ? portfolioResult.reason.message : `API status ${portfolioResult.value.status}`;
130
- logger.log('WARN', `[UPDATE] Failed to fetch PORTFOLIO for user ${userId}.`, { error: errorMsg });
135
+ // --- FIX: ENHANCED LOGGING ---
136
+ let errorMsg = 'Unknown fetch error';
137
+ let rawErrorText = 'N/A';
138
+
139
+ if (portfolioResult.status === 'rejected') {
140
+ errorMsg = portfolioResult.reason.message;
141
+ } else if (portfolioResult.value) {
142
+ errorMsg = portfolioResult.value.error?.message || `API status ${portfolioResult.value.status}`;
143
+ // Get the raw text from the proxy manager's response
144
+ if (typeof portfolioResult.value.text === 'function') {
145
+ rawErrorText = await portfolioResult.value.text();
146
+ }
147
+ }
148
+
149
+ logger.log('WARN', `[UPDATE] Failed to fetch PORTFOLIO for user ${userId}.`, {
150
+ error: errorMsg,
151
+ proxyResponse: rawErrorText // This will contain "urlfetch" or other quota messages
152
+ });
153
+ // --- END FIX ---
131
154
  }
132
155
 
133
156
  // --- Process History Result ---
@@ -135,11 +158,28 @@ async function handleUpdate(task, taskId, dependencies, config, username) {
135
158
  const historyData = await historyResult.value.json();
136
159
  wasHistorySuccess = true;
137
160
  // Add to history batch
161
+ console.log('DEBUG', `[UPDATE] SUCCESS Adding history data for user ${userId} to batch.`);
138
162
  await batchManager.addToTradingHistoryBatch(userId, portfolioStorageBlockId, today, historyData, userType);
139
163
  } else {
140
- // Log failure
141
- const errorMsg = historyResult.status === 'rejected' ? historyResult.reason.message : `API status ${historyResult.value.status}`;
142
- logger.log('WARN', `[UPDATE] Failed to fetch HISTORY for user ${userId} (${username}).`, { error: errorMsg });
164
+ // --- FIX: ENHANCED LOGGING ---
165
+ let errorMsg = 'Unknown fetch error';
166
+ let rawErrorText = 'N/A';
167
+
168
+ if (historyResult.status === 'rejected') {
169
+ errorMsg = historyResult.reason.message;
170
+ } else if (historyResult.value) {
171
+ errorMsg = historyResult.value.error?.message || `API status ${historyResult.value.status}`;
172
+ // Get the raw text from the proxy manager's response
173
+ if (typeof historyResult.value.text === 'function') {
174
+ rawErrorText = await historyResult.value.text();
175
+ }
176
+ }
177
+
178
+ logger.log('WARN', `[UPDATE] Failed to fetch HISTORY for user ${userId} (${username}).`, {
179
+ error: errorMsg,
180
+ proxyResponse: rawErrorText // This will contain "urlfetch" or other quota messages
181
+ });
182
+ // --- END FIX ---
143
183
  }
144
184
 
145
185
  // --- Handle Private User (if detected) ---
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bulltrackers-module",
3
- "version": "1.0.123",
3
+ "version": "1.0.124",
4
4
  "description": "Helper Functions for Bulltrackers.",
5
5
  "main": "index.js",
6
6
  "files": [