bulltrackers-module 1.0.732 → 1.0.734

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 (106) hide show
  1. package/functions/computation-system-v2/README.md +152 -0
  2. package/functions/computation-system-v2/computations/PopularInvestorProfileMetrics.js +720 -0
  3. package/functions/computation-system-v2/computations/PopularInvestorRiskAssessment.js +176 -0
  4. package/functions/computation-system-v2/computations/PopularInvestorRiskMetrics.js +294 -0
  5. package/functions/computation-system-v2/computations/TestComputation.js +46 -0
  6. package/functions/computation-system-v2/computations/UserPortfolioSummary.js +172 -0
  7. package/functions/computation-system-v2/config/bulltrackers.config.js +317 -0
  8. package/functions/computation-system-v2/framework/core/Computation.js +73 -0
  9. package/functions/computation-system-v2/framework/core/Manifest.js +223 -0
  10. package/functions/computation-system-v2/framework/core/RuleInjector.js +53 -0
  11. package/functions/computation-system-v2/framework/core/Rules.js +231 -0
  12. package/functions/computation-system-v2/framework/core/RunAnalyzer.js +163 -0
  13. package/functions/computation-system-v2/framework/cost/CostTracker.js +154 -0
  14. package/functions/computation-system-v2/framework/data/DataFetcher.js +399 -0
  15. package/functions/computation-system-v2/framework/data/QueryBuilder.js +232 -0
  16. package/functions/computation-system-v2/framework/data/SchemaRegistry.js +287 -0
  17. package/functions/computation-system-v2/framework/execution/Orchestrator.js +498 -0
  18. package/functions/computation-system-v2/framework/execution/TaskRunner.js +35 -0
  19. package/functions/computation-system-v2/framework/execution/middleware/CostTrackerMiddleware.js +32 -0
  20. package/functions/computation-system-v2/framework/execution/middleware/LineageMiddleware.js +32 -0
  21. package/functions/computation-system-v2/framework/execution/middleware/Middleware.js +14 -0
  22. package/functions/computation-system-v2/framework/execution/middleware/ProfilerMiddleware.js +47 -0
  23. package/functions/computation-system-v2/framework/index.js +45 -0
  24. package/functions/computation-system-v2/framework/lineage/LineageTracker.js +147 -0
  25. package/functions/computation-system-v2/framework/monitoring/Profiler.js +80 -0
  26. package/functions/computation-system-v2/framework/resilience/Checkpointer.js +66 -0
  27. package/functions/computation-system-v2/framework/scheduling/ScheduleValidator.js +327 -0
  28. package/functions/computation-system-v2/framework/storage/StateRepository.js +286 -0
  29. package/functions/computation-system-v2/framework/storage/StorageManager.js +469 -0
  30. package/functions/computation-system-v2/framework/storage/index.js +9 -0
  31. package/functions/computation-system-v2/framework/testing/ComputationTester.js +86 -0
  32. package/functions/computation-system-v2/framework/utils/Graph.js +205 -0
  33. package/functions/computation-system-v2/handlers/dispatcher.js +109 -0
  34. package/functions/computation-system-v2/handlers/index.js +23 -0
  35. package/functions/computation-system-v2/handlers/onDemand.js +289 -0
  36. package/functions/computation-system-v2/handlers/scheduler.js +327 -0
  37. package/functions/computation-system-v2/index.js +163 -0
  38. package/functions/computation-system-v2/rules/index.js +49 -0
  39. package/functions/computation-system-v2/rules/instruments.js +465 -0
  40. package/functions/computation-system-v2/rules/metrics.js +304 -0
  41. package/functions/computation-system-v2/rules/portfolio.js +534 -0
  42. package/functions/computation-system-v2/rules/rankings.js +655 -0
  43. package/functions/computation-system-v2/rules/social.js +562 -0
  44. package/functions/computation-system-v2/rules/trades.js +545 -0
  45. package/functions/computation-system-v2/scripts/migrate-sectors.js +73 -0
  46. package/functions/computation-system-v2/test/test-dispatcher.js +317 -0
  47. package/functions/computation-system-v2/test/test-framework.js +500 -0
  48. package/functions/computation-system-v2/test/test-real-execution.js +166 -0
  49. package/functions/computation-system-v2/test/test-real-integration.js +194 -0
  50. package/functions/computation-system-v2/test/test-refactor-e2e.js +131 -0
  51. package/functions/computation-system-v2/test/test-results.json +31 -0
  52. package/functions/computation-system-v2/test/test-risk-metrics-computation.js +329 -0
  53. package/functions/computation-system-v2/test/test-scheduler.js +204 -0
  54. package/functions/computation-system-v2/test/test-storage.js +449 -0
  55. package/functions/orchestrator/index.js +24 -30
  56. package/index.js +8 -29
  57. package/package.json +3 -2
  58. package/functions/computation-system/WorkflowOrchestrator.js +0 -213
  59. package/functions/computation-system/config/monitoring_config.js +0 -31
  60. package/functions/computation-system/config/validation_overrides.js +0 -10
  61. package/functions/computation-system/context/ContextFactory.js +0 -143
  62. package/functions/computation-system/context/ManifestBuilder.js +0 -379
  63. package/functions/computation-system/data/AvailabilityChecker.js +0 -236
  64. package/functions/computation-system/data/CachedDataLoader.js +0 -325
  65. package/functions/computation-system/data/DependencyFetcher.js +0 -455
  66. package/functions/computation-system/executors/MetaExecutor.js +0 -279
  67. package/functions/computation-system/executors/PriceBatchExecutor.js +0 -108
  68. package/functions/computation-system/executors/StandardExecutor.js +0 -465
  69. package/functions/computation-system/helpers/computation_dispatcher.js +0 -750
  70. package/functions/computation-system/helpers/computation_worker.js +0 -375
  71. package/functions/computation-system/helpers/monitor.js +0 -64
  72. package/functions/computation-system/helpers/on_demand_helpers.js +0 -154
  73. package/functions/computation-system/layers/extractors.js +0 -1097
  74. package/functions/computation-system/layers/index.js +0 -40
  75. package/functions/computation-system/layers/mathematics.js +0 -522
  76. package/functions/computation-system/layers/profiling.js +0 -537
  77. package/functions/computation-system/layers/validators.js +0 -170
  78. package/functions/computation-system/legacy/AvailabilityCheckerOld.js +0 -388
  79. package/functions/computation-system/legacy/CachedDataLoaderOld.js +0 -357
  80. package/functions/computation-system/legacy/DependencyFetcherOld.js +0 -478
  81. package/functions/computation-system/legacy/MetaExecutorold.js +0 -364
  82. package/functions/computation-system/legacy/StandardExecutorold.js +0 -476
  83. package/functions/computation-system/legacy/computation_dispatcherold.js +0 -944
  84. package/functions/computation-system/logger/logger.js +0 -297
  85. package/functions/computation-system/persistence/ContractValidator.js +0 -81
  86. package/functions/computation-system/persistence/FirestoreUtils.js +0 -56
  87. package/functions/computation-system/persistence/ResultCommitter.js +0 -283
  88. package/functions/computation-system/persistence/ResultsValidator.js +0 -130
  89. package/functions/computation-system/persistence/RunRecorder.js +0 -142
  90. package/functions/computation-system/persistence/StatusRepository.js +0 -52
  91. package/functions/computation-system/reporter_epoch.js +0 -6
  92. package/functions/computation-system/scripts/UpdateContracts.js +0 -128
  93. package/functions/computation-system/services/SnapshotService.js +0 -148
  94. package/functions/computation-system/simulation/Fabricator.js +0 -285
  95. package/functions/computation-system/simulation/SeededRandom.js +0 -41
  96. package/functions/computation-system/simulation/SimRunner.js +0 -51
  97. package/functions/computation-system/system_epoch.js +0 -2
  98. package/functions/computation-system/tools/BuildReporter.js +0 -531
  99. package/functions/computation-system/tools/ContractDiscoverer.js +0 -144
  100. package/functions/computation-system/tools/DeploymentValidator.js +0 -536
  101. package/functions/computation-system/tools/FinalSweepReporter.js +0 -322
  102. package/functions/computation-system/topology/HashManager.js +0 -55
  103. package/functions/computation-system/topology/ManifestLoader.js +0 -47
  104. package/functions/computation-system/utils/data_loader.js +0 -675
  105. package/functions/computation-system/utils/schema_capture.js +0 -121
  106. package/functions/computation-system/utils/utils.js +0 -188
@@ -1,325 +0,0 @@
1
- /**
2
- * @fileoverview Caching layer for data loading.
3
- * REFACTORED:
4
- * 1. Supports new BigQuery-backed loader functions.
5
- * 2. correctly passes 'userTypes' to portfolio/history loaders.
6
- * 3. Handles Virtual Shards for BigQuery prices.
7
- */
8
- const {
9
- loadDailyInsights,
10
- loadDailySocialPostInsights,
11
- getPriceShardRefs,
12
- getRelevantShardRefs,
13
- loadVerificationProfiles,
14
- loadPopularInvestorRankings,
15
- loadPIRatings,
16
- loadPIPageViews,
17
- loadWatchlistMembership,
18
- loadPIAlertHistory,
19
- loadPIWatchlistData,
20
- loadPopularInvestorMasterList,
21
- loadDailyPortfolios,
22
- loadDailyHistory
23
- } = require('../utils/data_loader');
24
- const { getAvailabilityWindow } = require('./AvailabilityChecker');
25
- const zlib = require('zlib');
26
-
27
- // =============================================================================
28
- // CONFIGURATION
29
- // =============================================================================
30
- const LOADER_DEFINITIONS = {
31
- loadRankings: {
32
- cache: 'rankings',
33
- configKey: 'popularInvestorRankingsCollection',
34
- defaultCol: 'popular_investor_rankings',
35
- fn: loadPopularInvestorRankings,
36
- flag: 'piRankings'
37
- },
38
- loadRatings: {
39
- cache: 'ratings',
40
- configKey: 'piRatingsCollection',
41
- defaultCol: 'pi_ratings',
42
- fn: loadPIRatings,
43
- flag: 'piRatings'
44
- },
45
- loadPageViews: {
46
- cache: 'pageViews',
47
- configKey: 'piPageViewsCollection',
48
- defaultCol: 'pi_page_views',
49
- fn: loadPIPageViews,
50
- flag: 'piPageViews'
51
- },
52
- loadWatchlistMembership: {
53
- cache: 'watchlistMembership',
54
- configKey: 'watchlistMembershipCollection',
55
- defaultCol: 'watchlist_membership',
56
- fn: loadWatchlistMembership,
57
- flag: 'watchlistMembership'
58
- },
59
- loadAlertHistory: {
60
- cache: 'alertHistory',
61
- configKey: 'piAlertHistoryCollection',
62
- defaultCol: 'pi_alert_history',
63
- fn: loadPIAlertHistory,
64
- flag: 'piAlertHistory'
65
- },
66
- loadInsights: {
67
- cache: 'insights',
68
- configKey: 'insightsCollectionName',
69
- defaultCol: 'daily_instrument_insights',
70
- fn: loadDailyInsights,
71
- flag: 'hasInsights'
72
- },
73
- loadSocial: {
74
- cache: 'social',
75
- configKey: 'socialInsightsCollection',
76
- defaultCol: 'daily_social_insights',
77
- fn: loadDailySocialPostInsights,
78
- flag: 'hasSocial'
79
- },
80
- loadPIWatchlistData: {
81
- cache: 'piWatchlistData',
82
- fn: loadPIWatchlistData,
83
- isIdBased: true
84
- },
85
- loadPortfolios: {
86
- cache: 'portfolios',
87
- fn: loadDailyPortfolios,
88
- flag: 'hasPortfolio' // Loose check, accurate check handles inside loader
89
- },
90
- loadHistory: {
91
- cache: 'history',
92
- fn: loadDailyHistory,
93
- flag: 'hasHistory'
94
- }
95
- };
96
-
97
- class CachedDataLoader {
98
- constructor(config, dependencies) {
99
- this.config = config;
100
- this.deps = dependencies;
101
-
102
- // Initialize caches
103
- this.cache = {
104
- mappings: null,
105
- verifications: null,
106
- piMasterList: null,
107
- prices: new Map(), // Dedicated cache for price shard data
108
- ...Object.values(LOADER_DEFINITIONS).reduce((acc, def) => {
109
- acc[def.cache] = new Map();
110
- return acc;
111
- }, {})
112
- };
113
- }
114
-
115
- _tryDecompress(data) {
116
- if (data?._compressed === true && data.payload) {
117
- try { return JSON.parse(zlib.gunzipSync(data.payload).toString()); }
118
- catch (e) { this.deps.logger?.log('WARN', '[CachedDataLoader] Decompression failed'); return {}; }
119
- }
120
- return data;
121
- }
122
-
123
- // =========================================================================
124
- // GENERIC LOADER
125
- // =========================================================================
126
- async _loadGeneric(methodName, key, ...args) {
127
- const def = LOADER_DEFINITIONS[methodName];
128
- if (!def) throw new Error(`Unknown loader method: ${methodName}`);
129
-
130
- // Construct a cache key that includes args (like userTypes) if present
131
- // e.g. "2025-01-01::POPULAR_INVESTOR"
132
- const cacheKey = args.length > 0 ? `${key}::${JSON.stringify(args)}` : key;
133
- const cacheMap = this.cache[def.cache];
134
-
135
- if (cacheMap.has(cacheKey)) return cacheMap.get(cacheKey);
136
-
137
- if (def.configKey && this.deps.logger) {
138
- // Only log simple date-based loads to avoid spam
139
- // this.deps.logger.log('INFO', `[CachedDataLoader] Loading ${def.cache} for ${key}`);
140
- }
141
-
142
- const promise = def.fn(this.config, this.deps, key, ...args);
143
- cacheMap.set(cacheKey, promise);
144
- return promise;
145
- }
146
-
147
- // =========================================================================
148
- // PUBLIC METHODS
149
- // =========================================================================
150
- async loadInsights(dateStr) { return this._loadGeneric('loadInsights', dateStr); }
151
- async loadSocial(dateStr, userTypes) { return this._loadGeneric('loadSocial', dateStr, userTypes); }
152
- async loadRankings(dateStr) { return this._loadGeneric('loadRankings', dateStr); }
153
- async loadRatings(dateStr) { return this._loadGeneric('loadRatings', dateStr); }
154
- async loadPageViews(dateStr) { return this._loadGeneric('loadPageViews', dateStr); }
155
- async loadWatchlistMembership(dateStr) { return this._loadGeneric('loadWatchlistMembership', dateStr); }
156
- async loadAlertHistory(dateStr) { return this._loadGeneric('loadAlertHistory', dateStr); }
157
- async loadPIWatchlistData(piCid) { return this._loadGeneric('loadPIWatchlistData', String(piCid)); }
158
- async loadPortfolios(dateStr, userTypes) { return this._loadGeneric('loadPortfolios', dateStr, userTypes); }
159
- async loadHistory(dateStr, userTypes) { return this._loadGeneric('loadHistory', dateStr, userTypes); }
160
-
161
- // =========================================================================
162
- // SPECIALIZED METHODS
163
- // =========================================================================
164
-
165
- async loadMappings() {
166
- if (this.cache.mappings) return this.cache.mappings;
167
- this.cache.mappings = await this.deps.calculationUtils.loadInstrumentMappings();
168
- return this.cache.mappings;
169
- }
170
-
171
- async loadVerifications(dateStr) {
172
- // Verifications are mostly static/global, but we accept dateStr for consistency
173
- if (this.cache.verifications) return this.cache.verifications;
174
- this.cache.verifications = await loadVerificationProfiles(this.config, this.deps, dateStr);
175
- return this.cache.verifications;
176
- }
177
-
178
- async loadPIMasterList() {
179
- if (this.cache.piMasterList) return this.cache.piMasterList;
180
- this.cache.piMasterList = await loadPopularInvestorMasterList(this.config, this.deps);
181
- return this.cache.piMasterList;
182
- }
183
-
184
- async getPriceShardReferences() {
185
- return getPriceShardRefs(this.config, this.deps);
186
- }
187
-
188
- async getSpecificPriceShardReferences(ids) {
189
- return getRelevantShardRefs(this.config, this.deps, ids);
190
- }
191
-
192
- async loadPriceShard(docRef) {
193
- // Handle BigQuery "Virtual Shard"
194
- if (docRef && docRef._bigquery === true) {
195
- // Use a dedicated cache key for the ALL-PRICE blob
196
- // If targetIds are specified, create a unique cache key
197
- const targetIds = docRef.targetIds && docRef.targetIds.length > 0 ? docRef.targetIds : null;
198
- const cacheKey = targetIds
199
- ? `BQ_PRICES_${targetIds.sort().join(',')}`
200
- : 'BQ_ALL_PRICES';
201
-
202
- if (this.cache.prices.has(cacheKey)) {
203
- return this.cache.prices.get(cacheKey);
204
- }
205
-
206
- const { queryAssetPrices } = require('../../core/utils/bigquery_utils');
207
- // queryAssetPrices signature: (startDateStr, endDateStr, instrumentIds, logger)
208
- const promise = queryAssetPrices(null, null, targetIds, this.deps.logger).then(data => {
209
- const result = data || {};
210
- this.cache.prices.set(cacheKey, result);
211
- return result;
212
- });
213
-
214
- return promise;
215
- }
216
-
217
- // Firestore Fallback
218
- try {
219
- const snap = await docRef.get();
220
- return snap.exists ? this._tryDecompress(snap.data()) : {};
221
- } catch (e) { return {}; }
222
- }
223
-
224
- // =========================================================================
225
- // SERIES LOADING (Batching)
226
- // =========================================================================
227
- async loadSeries(loaderMethod, dateStr, lookbackDays, ...args) {
228
- const def = LOADER_DEFINITIONS[loaderMethod];
229
- if (!def) throw new Error(`[CachedDataLoader] Unknown series method ${loaderMethod}`);
230
-
231
- // If method doesn't support batching configuration, use legacy loop
232
- if (!def.configKey || !def.flag) return this._loadSeriesLegacy(loaderMethod, dateStr, lookbackDays, ...args);
233
-
234
- // 1. Calculate Range
235
- const endDate = new Date(dateStr);
236
- const startDate = new Date(endDate);
237
- startDate.setUTCDate(startDate.getUTCDate() - (lookbackDays - 1));
238
-
239
- // 2. Check Availability
240
- let availabilityMap = new Map();
241
- try {
242
- availabilityMap = await getAvailabilityWindow(this.deps, startDate.toISOString().slice(0, 10), endDate.toISOString().slice(0, 10));
243
- } catch (e) {}
244
-
245
- const collectionName = this.config[def.configKey] || def.defaultCol;
246
- const batchRefs = [];
247
- const dateKeyMap = [];
248
-
249
- for (let i = 0; i < lookbackDays; i++) {
250
- const d = new Date(endDate);
251
- d.setUTCDate(d.getUTCDate() - i);
252
- const dString = d.toISOString().slice(0, 10);
253
-
254
- const dayStatus = availabilityMap.get(dString);
255
- if (!dayStatus || dayStatus[def.flag]) {
256
- batchRefs.push(this.deps.db.collection(collectionName).doc(dString));
257
- dateKeyMap.push(dString);
258
- }
259
- }
260
-
261
- // Note: Batch loading ONLY works for Firestore.
262
- // If we are in BigQuery mode, we should NOT use Firestore batching for these types.
263
- // However, this `loadSeries` method is mostly used for simple docs (Rankings, Ratings).
264
- // Since `loadRankings` in `data_loader.js` now points to BigQuery, passing a Firestore Ref
265
- // won't work because `data_loader` isn't called here; we are accessing DB directly.
266
-
267
- // [CRITICAL FIX]
268
- // If we are using BigQuery, we cannot use `db.getAll` on non-existent Firestore docs.
269
- // We must delegate back to the loader method (which handles BQ) in a loop (concurrently).
270
- if (process.env.BIGQUERY_ENABLED !== 'false') {
271
- return this._loadSeriesLegacy(loaderMethod, dateStr, lookbackDays, ...args);
272
- }
273
-
274
- // Firestore Batch Logic (Only runs if BQ Disabled)
275
- const results = {};
276
- if (batchRefs.length > 0) {
277
- try {
278
- const snapshots = await this.deps.db.getAll(...batchRefs);
279
- snapshots.forEach((snap, idx) => {
280
- if (snap.exists) {
281
- const raw = this._tryDecompress(snap.data());
282
- if (loaderMethod === 'loadRankings') results[dateKeyMap[idx]] = raw.Items || [];
283
- else results[dateKeyMap[idx]] = raw;
284
- }
285
- });
286
- } catch (err) {
287
- return this._loadSeriesLegacy(loaderMethod, dateStr, lookbackDays, ...args);
288
- }
289
- }
290
-
291
- return {
292
- dates: Object.keys(results).sort(),
293
- data: results,
294
- found: Object.keys(results).length,
295
- requested: lookbackDays
296
- };
297
- }
298
-
299
- async _loadSeriesLegacy(loaderMethod, dateStr, lookbackDays, ...args) {
300
- const results = {};
301
- const promises = [];
302
- const endDate = new Date(dateStr);
303
-
304
- for (let i = 0; i < lookbackDays; i++) {
305
- const d = new Date(endDate);
306
- d.setUTCDate(d.getUTCDate() - i);
307
- const dStr = d.toISOString().slice(0, 10);
308
- promises.push(
309
- this[loaderMethod](dStr, ...args)
310
- .then(data => { if (data) results[dStr] = data; })
311
- .catch(() => {})
312
- );
313
- }
314
-
315
- await Promise.all(promises);
316
- return {
317
- dates: Object.keys(results).sort(),
318
- data: results,
319
- found: Object.keys(results).length,
320
- requested: lookbackDays
321
- };
322
- }
323
- }
324
-
325
- module.exports = { CachedDataLoader };