@peopl-health/nexus 5.50.0 → 5.50.1

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.
@@ -5,16 +5,19 @@ const { decodeUnicodeEscapes } = require('../../utils/sanitizerUtils');
5
5
  const { Monitoreo_ID, Estado_General_ID, Symptoms_ID } = require('../../config/airtableConfig');
6
6
  const airtableService = require('../../services/airtableService');
7
7
  const { logger } = require('../../utils/logger');
8
- const { MapCache } = require('../../utils/MapCache');
9
8
  const { fieldEquals } = require('../../helpers/airtableFormulaHelper');
9
+ const { WriteClaimStore } = require('./writeClaimStore');
10
10
 
11
11
  const MIRROR_ATTEMPTS = 2;
12
- const recentIntakeCache = new MapCache({ maxSize: 1000, ttl: 15 * 60 * 1000 });
12
+ const INTAKE_WINDOW_MS = 15 * 60 * 1000;
13
+ const recentIntakeCache = new WriteClaimStore({ namespace: 'intake', ttlMs: INTAKE_WINDOW_MS, maxSize: 1000 });
13
14
  const EMERGENCY_MERGE_WINDOW_MS = 5 * 60 * 1000;
14
15
  const EMERGENCY_URGENCY_RANK = { routine: 0, urgent: 1, asap: 2, stat: 3 };
15
- const recentEmergencyCache = new MapCache({ maxSize: 500, ttl: EMERGENCY_MERGE_WINDOW_MS });
16
+ const recentEmergencyCache = new WriteClaimStore({ namespace: 'emergency', ttlMs: EMERGENCY_MERGE_WINDOW_MS, maxSize: 500 });
16
17
  const PAUSED_ALERT_WINDOW_MS = 4 * 60 * 60 * 1000;
17
- const recentPausedAlertCache = new MapCache({ maxSize: 1000, ttl: PAUSED_ALERT_WINDOW_MS });
18
+ const recentPausedAlertCache = new WriteClaimStore({ namespace: 'paused-alert', ttlMs: PAUSED_ALERT_WINDOW_MS, maxSize: 1000 });
19
+ const UNRESOLVED_WINDOW_MS = 30 * 60 * 1000;
20
+ const recentUnresolvedCache = new WriteClaimStore({ namespace: 'unresolved', ttlMs: UNRESOLVED_WINDOW_MS, maxSize: 1000 });
18
21
  const RECORD_ID_RX = /^rec[A-Za-z0-9]+$/;
19
22
 
20
23
  const MEDICAL_URGENCY_TO_EMERGENCY_LEVEL = {
@@ -85,10 +88,12 @@ async function findIntakePatientRecordId(code) {
85
88
  }
86
89
 
87
90
  async function recordUnresolvedRequest({ code, trace, question, details, resolutionAttempted = false, forDoctorOffice = false, category = null, urgency = null }) {
88
- return auditedWrite({
91
+ const fingerprint = createHash('sha1').update(`${code}\n${category || ''}\n${question || ''}`).digest('hex');
92
+ const written = await auditedWrite({
89
93
  trace,
90
94
  code,
91
95
  table: 'unresolved_questions',
96
+ skip: await recentUnresolvedCache.get(code) === fingerprint ? 'duplicate' : null,
92
97
  write: async () => {
93
98
  const patientId = await findMonitoreoPatientRecordId(code);
94
99
  const fields = {
@@ -104,10 +109,12 @@ async function recordUnresolvedRequest({ code, trace, question, details, resolut
104
109
  return airtableService.addRecord(Monitoreo_ID, 'unresolved_questions', [{ fields }], code);
105
110
  },
106
111
  });
112
+ if (written) await recentUnresolvedCache.set(code, fingerprint);
113
+ return written;
107
114
  }
108
115
 
109
116
  async function recordPausedThreadMessage({ code, text }) {
110
- if (recentPausedAlertCache.get(code)) return false;
117
+ if (await recentPausedAlertCache.get(code)) return false;
111
118
  const isWritten = await recordUnresolvedRequest({
112
119
  code,
113
120
  trace: null,
@@ -116,7 +123,7 @@ async function recordPausedThreadMessage({ code, text }) {
116
123
  category: 'contact_team_member',
117
124
  urgency: 'soon',
118
125
  });
119
- if (isWritten) recentPausedAlertCache.set(code, true);
126
+ if (isWritten) await recentPausedAlertCache.set(code, true);
120
127
  return isWritten;
121
128
  }
122
129
 
@@ -130,13 +137,13 @@ async function readEmergencyRow(recordId, code) {
130
137
  }
131
138
  }
132
139
 
133
- function rememberEmergency(code, recordId, urgencyFhir) {
134
- if (recordId && !isShadowRun()) recentEmergencyCache.set(code, { recordId, urgencyFhir });
140
+ async function rememberEmergency(code, recordId, urgencyFhir) {
141
+ if (recordId && !isShadowRun()) await recentEmergencyCache.set(code, { recordId, urgencyFhir });
135
142
  }
136
143
 
137
144
  async function recordEmergency({ code, trace, symptom, suspectedCondition = '', recommendedAction = '', urgencyFhir = null, urgencyLevel = null, documentation = '', mergeWithRecent = true }) {
138
145
  const level = urgencyLevel || MEDICAL_URGENCY_TO_EMERGENCY_LEVEL[urgencyFhir] || 'Alta';
139
- const prior = mergeWithRecent ? (recentEmergencyCache.get(code) || null) : null;
146
+ const prior = mergeWithRecent ? (await recentEmergencyCache.get(code) || null) : null;
140
147
  const rank = EMERGENCY_URGENCY_RANK[urgencyFhir];
141
148
  const priorRank = prior ? EMERGENCY_URGENCY_RANK[prior.urgencyFhir] : undefined;
142
149
  const mergeable = Boolean(prior) && rank !== undefined && priorRank !== undefined && rank <= priorRank;
@@ -167,7 +174,7 @@ async function recordEmergency({ code, trace, symptom, suspectedCondition = '',
167
174
  );
168
175
  if (updated?.length) {
169
176
  meta.mergedInto = prior.recordId;
170
- rememberEmergency(code, prior.recordId, urgencyFhir);
177
+ await rememberEmergency(code, prior.recordId, urgencyFhir);
171
178
  return updated;
172
179
  }
173
180
  }
@@ -175,7 +182,7 @@ async function recordEmergency({ code, trace, symptom, suspectedCondition = '',
175
182
  if (documentation) fields['Documentación_emergencia'] = documentation;
176
183
  const created = await airtableService.addRecord(Monitoreo_ID, 'emergencies', [{ fields }], code);
177
184
  const record = Array.isArray(created) ? created[0] : created;
178
- rememberEmergency(code, record?.id, mergeWithRecent ? urgencyFhir : null);
185
+ await rememberEmergency(code, record?.id, mergeWithRecent ? urgencyFhir : null);
179
186
  return created;
180
187
  },
181
188
  });
@@ -185,6 +192,7 @@ function _clearRecentIntakeCache() {
185
192
  recentIntakeCache.clear();
186
193
  recentEmergencyCache.clear();
187
194
  recentPausedAlertCache.clear();
195
+ recentUnresolvedCache.clear();
188
196
  }
189
197
 
190
198
  async function recordClinicalIntake({ code, trace, messageRaw, source = 'self', isLive = null }) {
@@ -195,7 +203,7 @@ async function recordClinicalIntake({ code, trace, messageRaw, source = 'self',
195
203
  code,
196
204
  isLive,
197
205
  table: 'intake',
198
- skip: recentIntakeCache.get(code) === fingerprint ? 'duplicate' : null,
206
+ skip: await recentIntakeCache.get(code) === fingerprint ? 'duplicate' : null,
199
207
  write: async () => {
200
208
  const patientId = await findIntakePatientRecordId(code);
201
209
  return airtableService.addRecord(Estado_General_ID, 'intake', [{
@@ -207,7 +215,7 @@ async function recordClinicalIntake({ code, trace, messageRaw, source = 'self',
207
215
  }], code);
208
216
  },
209
217
  });
210
- if (written) recentIntakeCache.set(code, fingerprint);
218
+ if (written) await recentIntakeCache.set(code, fingerprint);
211
219
  return written;
212
220
  }
213
221
 
@@ -0,0 +1,63 @@
1
+ const mongoose = require('mongoose');
2
+
3
+ const { WriteClaim } = require('../../models/writeClaimModel');
4
+ const { MapCache } = require('../../utils/MapCache');
5
+ const { logger } = require('../../utils/logger');
6
+
7
+ class WriteClaimStore {
8
+ constructor({ namespace, ttlMs, maxSize = 1000 } = {}) {
9
+ if (!namespace) throw new Error('WriteClaimStore requires a namespace');
10
+ if (!ttlMs) throw new Error('WriteClaimStore requires a ttlMs');
11
+ this.namespace = namespace;
12
+ this.ttlMs = ttlMs;
13
+ this.memory = new MapCache({ maxSize, ttl: ttlMs });
14
+ }
15
+
16
+ _key(key) {
17
+ return `${this.namespace}:${key}`;
18
+ }
19
+
20
+ _durable() {
21
+ return mongoose.connection?.readyState === 1;
22
+ }
23
+
24
+ async get(key) {
25
+ const local = this.memory.get(key);
26
+ if (local !== undefined) return local;
27
+ if (!this._durable()) return undefined;
28
+
29
+ try {
30
+ const claim = await WriteClaim.findOne({ key: this._key(key), expiresAt: { $gt: new Date() } }).lean();
31
+ if (!claim) return undefined;
32
+ this.memory.set(key, claim.value);
33
+ return claim.value;
34
+ } catch (error) {
35
+ logger.warn('[writeClaimStore] Durable read failed, falling back to memory', {
36
+ namespace: this.namespace, error: error.message,
37
+ });
38
+ return undefined;
39
+ }
40
+ }
41
+
42
+ async set(key, value) {
43
+ this.memory.set(key, value);
44
+ if (!this._durable()) return;
45
+ try {
46
+ await WriteClaim.updateOne(
47
+ { key: this._key(key) },
48
+ { $set: { value, expiresAt: new Date(Date.now() + this.ttlMs) } },
49
+ { upsert: true },
50
+ );
51
+ } catch (error) {
52
+ logger.warn('[writeClaimStore] Durable write failed, dedupe stays memory-only for this key', {
53
+ namespace: this.namespace, error: error.message,
54
+ });
55
+ }
56
+ }
57
+
58
+ clear() {
59
+ this.memory.clear();
60
+ }
61
+ }
62
+
63
+ module.exports = { WriteClaimStore };
@@ -0,0 +1,14 @@
1
+ const mongoose = require('mongoose');
2
+
3
+ const writeClaimSchema = new mongoose.Schema({
4
+ key: { type: String, required: true, unique: true },
5
+ value: { type: mongoose.Schema.Types.Mixed, default: null },
6
+ expiresAt: { type: Date, required: true },
7
+ createdAt: { type: Date, default: Date.now }
8
+ });
9
+
10
+ writeClaimSchema.index({ expiresAt: 1 }, { name: 'write_claim_ttl_idx', expireAfterSeconds: 0 });
11
+
12
+ const WriteClaim = mongoose.model('WriteClaim', writeClaimSchema);
13
+
14
+ module.exports = { WriteClaim };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.50.0",
3
+ "version": "5.50.1",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",