@lyxa.ai/core 1.2.23 → 1.2.25
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.
- package/dist/libraries/map/interfaces/IMapService.d.ts +8 -0
- package/dist/libraries/map/interfaces/IMapService.js.map +1 -1
- package/dist/libraries/map/mapService.d.ts +2 -1
- package/dist/libraries/map/mapService.js +3 -0
- package/dist/libraries/map/mapService.js.map +1 -1
- package/dist/libraries/map/providers/google-maps.d.ts +11 -2
- package/dist/libraries/map/providers/google-maps.js +164 -2
- package/dist/libraries/map/providers/google-maps.js.map +1 -1
- package/dist/libraries/socket/core/socket-event-consumer.js +4 -1
- package/dist/libraries/socket/core/socket-event-consumer.js.map +1 -1
- package/dist/libraries/socket/core/socket-event-publisher.d.ts +1 -1
- package/dist/libraries/socket/core/socket-event-publisher.js +38 -20
- package/dist/libraries/socket/core/socket-event-publisher.js.map +1 -1
- package/dist/libraries/socket/core/socket-event-registry.map.js.map +1 -1
- package/dist/libraries/socket/core/socket-redis-connections.d.ts +3 -1
- package/dist/libraries/socket/core/socket-redis-connections.js +170 -116
- package/dist/libraries/socket/core/socket-redis-connections.js.map +1 -1
- package/dist/types/README.md +1 -1
- package/dist/types/package.json +1 -1
- package/package.json +1 -1
|
@@ -25,7 +25,15 @@ export interface IWaypointDistanceInfo {
|
|
|
25
25
|
legs: Array<ILeg>;
|
|
26
26
|
overviewPolyline: Array<[number, number]>;
|
|
27
27
|
}
|
|
28
|
+
export interface IRouteMatrixDTO {
|
|
29
|
+
distance: IDistance;
|
|
30
|
+
duration: IDuration;
|
|
31
|
+
condition: string;
|
|
32
|
+
originIndex: number;
|
|
33
|
+
destinationIndex: number;
|
|
34
|
+
}
|
|
28
35
|
export interface IMapService {
|
|
29
36
|
getDistanceInfo(origin: ICoordinate, destination: ICoordinate): Promise<IDistanceInfo>;
|
|
30
37
|
getWaypointsDistanceInfo(origin: ICoordinate, destination: ICoordinate, waypoints: Array<ICoordinate>): Promise<IWaypointDistanceInfo>;
|
|
38
|
+
getDistanceMatrix(origins: Array<ICoordinate>, destinations: Array<ICoordinate>): Promise<IRouteMatrixDTO[]>;
|
|
31
39
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"IMapService.js","sourceRoot":"/","sources":["libraries/map/interfaces/IMapService.ts"],"names":[],"mappings":"","sourcesContent":["export interface ICoordinate {\n\tlongitude: number;\n\tlatitude: number;\n}\n\nexport interface IDistance {\n\tvalue: number;\n\ttext: string;\n}\n\nexport interface IDuration {\n\tvalue: number;\n\ttext: string;\n}\n\nexport interface ILeg {\n\tdistance: IDistance;\n\tduration: IDuration;\n\toverviewPolyline: Array<[number, number]>;\n}\n\nexport interface IDistanceInfo {\n\tdistance: IDistance;\n\tduration: IDuration;\n}\n\nexport interface IWaypointDistanceInfo {\n\tdistance: IDistance;\n\tduration: IDuration;\n\tlegs: Array<ILeg>;\n\toverviewPolyline: Array<[number, number]>;\n}\n\nexport interface
|
|
1
|
+
{"version":3,"file":"IMapService.js","sourceRoot":"/","sources":["libraries/map/interfaces/IMapService.ts"],"names":[],"mappings":"","sourcesContent":["export interface ICoordinate {\n\tlongitude: number;\n\tlatitude: number;\n}\n\nexport interface IDistance {\n\tvalue: number;\n\ttext: string;\n}\n\nexport interface IDuration {\n\tvalue: number;\n\ttext: string;\n}\n\nexport interface ILeg {\n\tdistance: IDistance;\n\tduration: IDuration;\n\toverviewPolyline: Array<[number, number]>;\n}\n\nexport interface IDistanceInfo {\n\tdistance: IDistance;\n\tduration: IDuration;\n}\n\nexport interface IWaypointDistanceInfo {\n\tdistance: IDistance;\n\tduration: IDuration;\n\tlegs: Array<ILeg>;\n\toverviewPolyline: Array<[number, number]>;\n}\n\nexport interface IRouteMatrixDTO {\n\tdistance: IDistance;\n\tduration: IDuration;\n\tcondition: string;\n\toriginIndex: number;\n\tdestinationIndex: number;\n}\n\nexport interface IMapService {\n\tgetDistanceInfo(origin: ICoordinate, destination: ICoordinate): Promise<IDistanceInfo>;\n\n\tgetWaypointsDistanceInfo(\n\t\torigin: ICoordinate,\n\t\tdestination: ICoordinate,\n\t\twaypoints: Array<ICoordinate>\n\t): Promise<IWaypointDistanceInfo>;\n\n\tgetDistanceMatrix(origins: Array<ICoordinate>, destinations: Array<ICoordinate>): Promise<IRouteMatrixDTO[]>;\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { IMapService, ICoordinate, IDistanceInfo, IWaypointDistanceInfo } from './interfaces/IMapService';
|
|
1
|
+
import { IMapService, ICoordinate, IDistanceInfo, IWaypointDistanceInfo, IRouteMatrixDTO } from './interfaces/IMapService';
|
|
2
2
|
export declare class MapService {
|
|
3
3
|
private service;
|
|
4
4
|
constructor(service: IMapService);
|
|
@@ -6,4 +6,5 @@ export declare class MapService {
|
|
|
6
6
|
calculateDistanceBetweenCoordinates(coord1: [number, number], coord2: [number, number]): Promise<number>;
|
|
7
7
|
getDistanceInfo(origin: ICoordinate, destination: ICoordinate): Promise<IDistanceInfo>;
|
|
8
8
|
getWaypointsDistanceInfo(origin: ICoordinate, destination: ICoordinate, waypoints: Array<ICoordinate>): Promise<IWaypointDistanceInfo>;
|
|
9
|
+
getDistanceMatrix(origins: Array<ICoordinate>, destinations: Array<ICoordinate>): Promise<IRouteMatrixDTO[]>;
|
|
9
10
|
}
|
|
@@ -51,6 +51,9 @@ let MapService = class MapService {
|
|
|
51
51
|
async getWaypointsDistanceInfo(origin, destination, waypoints) {
|
|
52
52
|
return await this.service.getWaypointsDistanceInfo(origin, destination, waypoints);
|
|
53
53
|
}
|
|
54
|
+
async getDistanceMatrix(origins, destinations) {
|
|
55
|
+
return await this.service.getDistanceMatrix(origins, destinations);
|
|
56
|
+
}
|
|
54
57
|
};
|
|
55
58
|
exports.MapService = MapService;
|
|
56
59
|
exports.MapService = MapService = __decorate([
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mapService.js","sourceRoot":"/","sources":["libraries/map/mapService.ts"],"names":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inate, IDistanceInfo, IWaypointDistanceInfo, IRouteMatrixDTO } from './interfaces/IMapService';\n\n@Service()\nexport class MapService {\n\tconstructor(private service: IMapService) {}\n\n\t/**\n\t * Calculates the distance between two coordinates in kilometers\n\t * using the Haversine formula\n\t *\n\t * @param coord1 - First coordinate [latitude, longitude]\n\t * @param coord2 - Second coordinate [latitude, longitude]\n\t * @returns Distance in kilometers\n\t */\n\tpublic calculateHaversineDistance(coord1: [number, number], coord2: [number, number]): number {\n\t\tconst [lat1, lon1] = coord1;\n\t\tconst [lat2, lon2] = coord2;\n\n\t\t// Earth radius in kilometers\n\t\tconst R = 6371;\n\n\t\t// Convert degrees to radians\n\t\tconst dLat = ((lat2 - lat1) * Math.PI) / 180;\n\t\tconst dLon = ((lon2 - lon1) * Math.PI) / 180;\n\n\t\tconst a =\n\t\t\tMath.sin(dLat / 2) * Math.sin(dLat / 2) +\n\t\t\tMath.cos((lat1 * Math.PI) / 180) *\n\t\t\t\tMath.cos((lat2 * Math.PI) / 180) *\n\t\t\t\tMath.sin(dLon / 2) *\n\t\t\t\tMath.sin(dLon / 2);\n\n\t\tconst c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));\n\n\t\treturn R * c;\n\t}\n\n\t/**\n\t * Calculates the distance between two coordinates in kilometers\n\t * using the Haversine formula\n\t *\n\t * @param coord1 - First coordinate [latitude, longitude]\n\t * @param coord2 - Second coordinate [latitude, longitude]\n\t * @returns Distance in kilometers\n\t */\n\tpublic async calculateDistanceBetweenCoordinates(\n\t\tcoord1: [number, number],\n\t\tcoord2: [number, number]\n\t): Promise<number> {\n\t\tconst [lat1, lon1] = coord1;\n\t\tconst [lat2, lon2] = coord2;\n\n\t\ttry {\n\t\t\tconst distanceInfo = await this.service.getDistanceInfo(\n\t\t\t\t{ latitude: lat1, longitude: lon1 },\n\t\t\t\t{ latitude: lat2, longitude: lon2 }\n\t\t\t);\n\t\t\tif (distanceInfo && distanceInfo.distance) {\n\t\t\t\treturn distanceInfo.distance.value / 1000; // Convert meters to kilometers\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tconsole.error(`Error fetching distance info: ${error}`);\n\t\t}\n\n\t\t// Fallback to Haversine formula if API call fails\n\t\tconsole.log('Maps API failed. Falling back to Haversine calculation.');\n\t\treturn this.calculateHaversineDistance(coord1, coord2);\n\t}\n\n\t/**\n\t * Get the distance and driving duration between two locations\n\t *\n\t * @param origin - Origin coordinate\n\t * @param destination - Destination coordinate\n\t * @returns Distance and duration\n\t */\n\tasync getDistanceInfo(origin: ICoordinate, destination: ICoordinate): Promise<IDistanceInfo> {\n\t\treturn await this.service.getDistanceInfo(origin, destination);\n\t}\n\n\t/**\n\t * Get the distance and driving duration between two locations\n\t *\n\t * @param origin - Origin coordinate\n\t * @param destination - Destination coordinate\n\t * @param waypoints - Coordinates of intermediary waypoints\n\t * @returns Distance, duration, and polyline of each leg and the whole journey\n\t */\n\tasync getWaypointsDistanceInfo(\n\t\torigin: ICoordinate,\n\t\tdestination: ICoordinate,\n\t\twaypoints: Array<ICoordinate>\n\t): Promise<IWaypointDistanceInfo> {\n\t\treturn await this.service.getWaypointsDistanceInfo(origin, destination, waypoints);\n\t}\n\n\tasync getDistanceMatrix(\n\t\torigins: Array<ICoordinate>,\n\t\tdestinations: Array<ICoordinate>\n\t): Promise<IRouteMatrixDTO[]> {\n\t\treturn await this.service.getDistanceMatrix(origins, destinations);\n\t}\n\n}\n"]}
|
|
@@ -1,9 +1,11 @@
|
|
|
1
|
-
import { IMapService, ICoordinate, IDistanceInfo, IWaypointDistanceInfo } from '../interfaces/IMapService';
|
|
1
|
+
import { IMapService, ICoordinate, IDistanceInfo, IWaypointDistanceInfo, IRouteMatrixDTO } from '../interfaces/IMapService';
|
|
2
2
|
import { RedisService } from '../../redis';
|
|
3
3
|
export declare class GoogleMapsService implements IMapService {
|
|
4
4
|
private redisService;
|
|
5
5
|
private _apiKey;
|
|
6
6
|
private logModel;
|
|
7
|
+
private _routeURL;
|
|
8
|
+
private _routeMatrixURL;
|
|
7
9
|
constructor(redisService: RedisService, apiKey: string);
|
|
8
10
|
private createCacheKey;
|
|
9
11
|
private acquireDistributedLock;
|
|
@@ -12,7 +14,14 @@ export declare class GoogleMapsService implements IMapService {
|
|
|
12
14
|
private clearRouteCache;
|
|
13
15
|
private getCacheStats;
|
|
14
16
|
getDistanceInfo(origin: ICoordinate, destination: ICoordinate): Promise<IDistanceInfo>;
|
|
15
|
-
private
|
|
17
|
+
private getDistanceInfoFromGoogle_DEPRECATED;
|
|
16
18
|
getWaypointsDistanceInfo(origin: ICoordinate, destination: ICoordinate, waypoints: Array<ICoordinate>): Promise<IWaypointDistanceInfo>;
|
|
19
|
+
private getWaypointsDistanceInfoFromGoogle_DEPRECATED;
|
|
20
|
+
getDistanceMatrix(origins: Array<ICoordinate>, destinations: Array<ICoordinate>): Promise<IRouteMatrixDTO[]>;
|
|
21
|
+
private getDistanceInfoFromGoogle;
|
|
17
22
|
private getWaypointsDistanceInfoFromGoogle;
|
|
23
|
+
private toLocation;
|
|
24
|
+
private toWaypoint;
|
|
25
|
+
private toDurationDTO;
|
|
26
|
+
private toDistanceDTO;
|
|
18
27
|
}
|
|
@@ -60,6 +60,8 @@ let GoogleMapsService = class GoogleMapsService {
|
|
|
60
60
|
redisService;
|
|
61
61
|
_apiKey;
|
|
62
62
|
logModel;
|
|
63
|
+
_routeURL = 'https://routes.googleapis.com/directions/v2:computeRoutes';
|
|
64
|
+
_routeMatrixURL = 'https://routes.googleapis.com/distanceMatrix/v2:computeRouteMatrix';
|
|
63
65
|
constructor(redisService, apiKey) {
|
|
64
66
|
this.redisService = redisService;
|
|
65
67
|
this._apiKey = apiKey;
|
|
@@ -175,7 +177,7 @@ let GoogleMapsService = class GoogleMapsService {
|
|
|
175
177
|
});
|
|
176
178
|
}
|
|
177
179
|
}
|
|
178
|
-
async
|
|
180
|
+
async getDistanceInfoFromGoogle_DEPRECATED(origin, destination) {
|
|
179
181
|
try {
|
|
180
182
|
const url = `https://maps.googleapis.com/maps/api/directions/json?origin=${origin.latitude}, ${origin.longitude}&destination=${destination.latitude}, ${destination.longitude}&key=${this._apiKey}&mode=DRIVING`;
|
|
181
183
|
const { data } = await axios_1.default.get(url);
|
|
@@ -254,7 +256,7 @@ let GoogleMapsService = class GoogleMapsService {
|
|
|
254
256
|
});
|
|
255
257
|
}
|
|
256
258
|
}
|
|
257
|
-
async
|
|
259
|
+
async getWaypointsDistanceInfoFromGoogle_DEPRECATED(origin, destination, waypoints) {
|
|
258
260
|
try {
|
|
259
261
|
const waypointsStr = waypoints.map(point => `${point.latitude},${point.longitude}`).join('|');
|
|
260
262
|
const url = `https://maps.googleapis.com/maps/api/directions/json?origin=${origin.latitude},${origin.longitude}&destination=${destination.latitude},${destination.longitude}&waypoints=${waypointsStr}&key=${this._apiKey}&mode=DRIVING`;
|
|
@@ -295,6 +297,166 @@ let GoogleMapsService = class GoogleMapsService {
|
|
|
295
297
|
});
|
|
296
298
|
}
|
|
297
299
|
}
|
|
300
|
+
async getDistanceMatrix(origins, destinations) {
|
|
301
|
+
try {
|
|
302
|
+
const body = {
|
|
303
|
+
origins: origins.map(this.toWaypoint),
|
|
304
|
+
destinations: destinations.map(this.toWaypoint),
|
|
305
|
+
travelMode: 'DRIVE',
|
|
306
|
+
routingPreference: 'TRAFFIC_AWARE',
|
|
307
|
+
};
|
|
308
|
+
const fieldMask = 'originIndex,destinationIndex,duration,distanceMeters,condition';
|
|
309
|
+
const response = await axios_1.default.post(this._routeMatrixURL, body, {
|
|
310
|
+
headers: {
|
|
311
|
+
'Content-Type': 'application/json',
|
|
312
|
+
'X-Goog-Api-Key': this._apiKey,
|
|
313
|
+
'X-Goog-FieldMask': fieldMask,
|
|
314
|
+
},
|
|
315
|
+
});
|
|
316
|
+
const results = response.data.map((item) => {
|
|
317
|
+
const distance = this.toDistanceDTO(item.distanceMeters ?? 0);
|
|
318
|
+
const duration = this.toDurationDTO(item.duration ?? '0s');
|
|
319
|
+
return {
|
|
320
|
+
distance,
|
|
321
|
+
duration,
|
|
322
|
+
condition: item.condition,
|
|
323
|
+
originIndex: item.originIndex,
|
|
324
|
+
destinationIndex: item.destinationIndex,
|
|
325
|
+
};
|
|
326
|
+
});
|
|
327
|
+
return results;
|
|
328
|
+
}
|
|
329
|
+
catch (error) {
|
|
330
|
+
console.error(`Error in getDistanceMatrix: ${error}`);
|
|
331
|
+
}
|
|
332
|
+
return [];
|
|
333
|
+
}
|
|
334
|
+
async getDistanceInfoFromGoogle(origin, destination) {
|
|
335
|
+
try {
|
|
336
|
+
const body = {
|
|
337
|
+
origin: this.toLocation(origin),
|
|
338
|
+
destination: this.toLocation(destination),
|
|
339
|
+
travelMode: 'DRIVE',
|
|
340
|
+
routingPreference: 'TRAFFIC_AWARE',
|
|
341
|
+
computeAlternativeRoutes: false,
|
|
342
|
+
routeModifiers: {
|
|
343
|
+
avoidTolls: false,
|
|
344
|
+
avoidHighways: false,
|
|
345
|
+
avoidFerries: false,
|
|
346
|
+
},
|
|
347
|
+
languageCode: 'en-US',
|
|
348
|
+
units: 'METRIC',
|
|
349
|
+
};
|
|
350
|
+
console.log('Request body for getDistanceInfo V2:', body);
|
|
351
|
+
const fieldMask = 'routes.duration,routes.distanceMeters';
|
|
352
|
+
const response = await axios_1.default.post(this._routeURL, body, {
|
|
353
|
+
headers: {
|
|
354
|
+
'Content-Type': 'application/json',
|
|
355
|
+
'X-Goog-Api-Key': this._apiKey,
|
|
356
|
+
'X-Goog-FieldMask': fieldMask,
|
|
357
|
+
},
|
|
358
|
+
});
|
|
359
|
+
console.log('Response from getDistanceInfo V2:', response.data);
|
|
360
|
+
const route = response.data.routes[0];
|
|
361
|
+
const distance = this.toDistanceDTO(route.distanceMeters);
|
|
362
|
+
const duration = this.toDurationDTO(route.duration);
|
|
363
|
+
return { distance, duration };
|
|
364
|
+
}
|
|
365
|
+
catch (error) {
|
|
366
|
+
console.error(`Error in getDistanceInfo V2: ${error}`);
|
|
367
|
+
throw new server_1.TRPCError({
|
|
368
|
+
code: 'INTERNAL_SERVER_ERROR',
|
|
369
|
+
message: 'Failed to fetch distance information from Google Maps API.',
|
|
370
|
+
});
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
async getWaypointsDistanceInfoFromGoogle(origin, destination, waypoints) {
|
|
374
|
+
try {
|
|
375
|
+
const body = {
|
|
376
|
+
origin: this.toLocation(origin),
|
|
377
|
+
destination: this.toLocation(destination),
|
|
378
|
+
intermediates: waypoints.map(this.toLocation),
|
|
379
|
+
travelMode: 'DRIVE',
|
|
380
|
+
routingPreference: 'TRAFFIC_AWARE',
|
|
381
|
+
computeAlternativeRoutes: false,
|
|
382
|
+
routeModifiers: {
|
|
383
|
+
avoidTolls: false,
|
|
384
|
+
avoidHighways: false,
|
|
385
|
+
avoidFerries: false,
|
|
386
|
+
},
|
|
387
|
+
languageCode: 'en-US',
|
|
388
|
+
units: 'METRIC',
|
|
389
|
+
};
|
|
390
|
+
console.log('Request body for getDistanceInfo V2:', body);
|
|
391
|
+
const fieldMask = 'routes';
|
|
392
|
+
const response = await axios_1.default.post(this._routeURL, body, {
|
|
393
|
+
headers: {
|
|
394
|
+
'Content-Type': 'application/json',
|
|
395
|
+
'X-Goog-Api-Key': this._apiKey,
|
|
396
|
+
'X-Goog-FieldMask': fieldMask,
|
|
397
|
+
},
|
|
398
|
+
});
|
|
399
|
+
console.log('Response from getWaypointDistanceInfo V2:', JSON.stringify(response.data));
|
|
400
|
+
const route = response.data.routes[0];
|
|
401
|
+
const distance = this.toDistanceDTO(route.distanceMeters);
|
|
402
|
+
const duration = this.toDurationDTO(route.duration);
|
|
403
|
+
const overviewPolyline = polyline.decode(route.polyline.encodedPolyline);
|
|
404
|
+
const legs = (route?.legs ?? []).map((leg) => {
|
|
405
|
+
const overviewPolyline = polyline.decode(leg.polyline.encodedPolyline);
|
|
406
|
+
const legDistance = this.toDistanceDTO(leg.distanceMeters);
|
|
407
|
+
const legDuration = this.toDurationDTO(leg.duration);
|
|
408
|
+
return {
|
|
409
|
+
distance: legDistance,
|
|
410
|
+
duration: legDuration,
|
|
411
|
+
overviewPolyline,
|
|
412
|
+
};
|
|
413
|
+
});
|
|
414
|
+
return { distance, duration, overviewPolyline, legs };
|
|
415
|
+
}
|
|
416
|
+
catch (error) {
|
|
417
|
+
console.error(`Error in getWaypointDistanceInfo V2: ${error}`);
|
|
418
|
+
throw new server_1.TRPCError({
|
|
419
|
+
code: 'INTERNAL_SERVER_ERROR',
|
|
420
|
+
message: 'Failed to fetch waypoint distance information from Google Maps API.',
|
|
421
|
+
});
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
toLocation(coord) {
|
|
425
|
+
return { location: { latLng: { latitude: coord.latitude, longitude: coord.longitude } } };
|
|
426
|
+
}
|
|
427
|
+
toWaypoint(coord) {
|
|
428
|
+
return { waypoint: { location: { latLng: { latitude: coord.latitude, longitude: coord.longitude } } } };
|
|
429
|
+
}
|
|
430
|
+
toDurationDTO(duration) {
|
|
431
|
+
const durationSeconds = parseInt(duration.replace('s', ''));
|
|
432
|
+
const hours = Math.floor(durationSeconds / 3600);
|
|
433
|
+
const minutes = Math.ceil((durationSeconds % 3600) / 60);
|
|
434
|
+
const durationText = durationSeconds
|
|
435
|
+
? durationSeconds < 60
|
|
436
|
+
? `1 min`
|
|
437
|
+
: durationSeconds < 3600
|
|
438
|
+
? minutes === 1
|
|
439
|
+
? '1 min'
|
|
440
|
+
: `${minutes} mins`
|
|
441
|
+
: hours === 1
|
|
442
|
+
? minutes === 0
|
|
443
|
+
? '1 hour'
|
|
444
|
+
: minutes === 1
|
|
445
|
+
? '1 hour 1 min'
|
|
446
|
+
: `1 hour ${minutes} mins`
|
|
447
|
+
: minutes === 0
|
|
448
|
+
? `${hours} hours`
|
|
449
|
+
: minutes === 1
|
|
450
|
+
? `${hours} hours 1 min`
|
|
451
|
+
: `${hours} hours ${minutes} mins`
|
|
452
|
+
: '1 min';
|
|
453
|
+
return { value: durationSeconds, text: durationText };
|
|
454
|
+
}
|
|
455
|
+
toDistanceDTO(distanceMeters) {
|
|
456
|
+
const distanceValue = distanceMeters;
|
|
457
|
+
const distanceText = `${(distanceMeters / 1000).toFixed(1)} km`;
|
|
458
|
+
return { value: distanceValue, text: distanceText };
|
|
459
|
+
}
|
|
298
460
|
};
|
|
299
461
|
exports.GoogleMapsService = GoogleMapsService;
|
|
300
462
|
exports.GoogleMapsService = GoogleMapsService = __decorate([
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"google-maps.js","sourceRoot":"/","sources":["libraries/map/providers/google-maps.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,kDAA0B;AAU1B,2DAA6C;AAC7C,yCAAyC;AACzC,uCAA2C;AAC3C,mCAAiD;AACjD,mCAAgC;AAChC,+CAA0D;AAE1D,IAAa,iBAAiB,GAA9B,MAAa,iBAAiB;IAKQ;IAJ7B,OAAO,CAAqB;IAC5B,QAAQ,CAA8B;IAE9C,YACqC,YAA0B,EAC9D,MAAc;QADsB,iBAAY,GAAZ,YAAY,CAAc;QAG9D,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC;QACtB,IAAI,CAAC,QAAQ,GAAG,6BAAmD,CAAC;IACrE,CAAC;IAEO,cAAc,CAAC,MAAmB,EAAE,WAAwB,EAAE,YAA2B,EAAE;QAClG,MAAM,SAAS,GAAG,GAAG,MAAM,CAAC,QAAQ,IAAI,MAAM,CAAC,SAAS,EAAE,CAAC;QAC3D,MAAM,cAAc,GAAG,GAAG,WAAW,CAAC,QAAQ,IAAI,WAAW,CAAC,SAAS,EAAE,CAAC;QAE1E,IAAI,OAAO,GAAG,EAAE,MAAM,EAAE,SAAS,EAAE,WAAW,EAAE,cAAc,EAAE,SAAS,EAAE,EAAc,EAAE,CAAC;QAE5F,IAAI,SAAS,IAAI,SAAS,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YACvC,OAAO,CAAC,SAAS,GAAG,SAAS,CAAC,G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,EAAE,GAAG,CAAC,aAAa,GAAG,IAAI,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,KAAK;gBAC/C,KAAK,EAAE,aAAa;aACpB,CAAC;YAEF,MAAM,aAAa,GAAG,IAAI,EAAE,MAAM,CACjC,CAAC,GAAQ,EAAE,IAAkC,EAAE,EAAE,CAAC,GAAG,GAAG,IAAI,CAAC,QAAQ,CAAC,KAAK,EAC3E,CAAC,CACD,CAAC;YACF,MAAM,QAAQ,GAAG;gBAChB,IAAI,EAAE,GAAG,IAAI,CAAC,KAAK,CAAC,aAAa,GAAG,EAAE,CAAC,OAAO;gBAC9C,KAAK,EAAE,aAAa;aACpB,CAAC;YAEF,IAAI,CAAC,QAAQ,IAAI,CAAC,QAAQ,EAAE,CAAC;gBAC5B,MAAM,IAAI,kBAAS,CAAC;oBACnB,IAAI,EAAE,uBAAuB;oBAC7B,OAAO,EAAE,4CAA4C;iBACrD,CAAC,CAAC;YACJ,CAAC;YAED,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,gBAAgB,EAAE,CAAC;QACvD,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YAChB,OAAO,CAAC,KAAK,CAAC,sCAAsC,KAAK,EAAE,CAAC,CAAC;YAC7D,MAAM,IAAI,kBAAS,CAAC;gBACnB,IAAI,EAAE,uBAAuB;gBAC7B,OAAO,EAAE,qEAAqE;aAC9E,CAAC,CAAC;QACJ,CAAC;IACF,CAAC;CACD,CAAA;AA/VY,8CAAiB;4BAAjB,iBAAiB;IAK3B,WAAA,IAAA,eAAM,EAAC,GAAG,EAAE,CAAC,oBAAY,CAAC,CAAA;qCAAuB,oBAAY;GALnD,iBAAiB,CA+V7B","sourcesContent":["import axios from 'axios';\nimport {\n\tIMapService,\n\tICoordinate,\n\tIDistance,\n\tIDuration,\n\tILeg,\n\tIDistanceInfo,\n\tIWaypointDistanceInfo,\n} from '../interfaces/IMapService';\nimport * as polyline from '@mapbox/polyline';\nimport { TRPCError } from '@trpc/server';\nimport { RedisService } from '../../redis';\nimport { createHash, randomBytes } from 'crypto';\nimport { Inject } from 'typedi';\nimport { GoogleMapsUsageModel } from '../../mongo/models';\n\nexport class GoogleMapsService implements IMapService {\n\tprivate _apiKey: string | undefined;\n\tprivate logModel: typeof GoogleMapsUsageModel;\n\n\tconstructor(\n\t\t@Inject(() => RedisService) private redisService: RedisService,\n\t\tapiKey: string\n\t) {\n\t\tthis._apiKey = apiKey;\n\t\tthis.logModel = GoogleMapsUsageModel as typeof GoogleMapsUsageModel;\n\t}\n\n\tprivate createCacheKey(origin: ICoordinate, destination: ICoordinate, waypoints: ICoordinate[] = []) {\n\t\tconst originKey = `${origin.latitude},${origin.longitude}`;\n\t\tconst destinationKey = `${destination.latitude},${destination.longitude}`;\n\n\t\tlet keyData = { origin: originKey, destination: destinationKey, waypoints: [] as string[] };\n\n\t\tif (waypoints && waypoints.length > 0) {\n\t\t\tkeyData.waypoints = waypoints.map(point => `${point.latitude},${point.longitude}`).sort();\n\t\t}\n\n\t\treturn createHash('md5').update(JSON.stringify(keyData)).digest('hex');\n\t}\n\n\tprivate async acquireDistributedLock(key: string, ttl = 10) {\n\t\tconst token = randomBytes(16).toString('hex');\n\t\tconst lockKey = `lock:${key}`;\n\n\t\tconst result = await this.redisService.redisClient.set(lockKey, token, 'EX', ttl, 'NX');\n\t\treturn result ? { token, lockKey } : null;\n\t}\n\n\tprivate async releaseDistributedLock(lockKey: string, token: string) {\n\t\tconst lua = `\n if redis.call(\"get\", KEYS[1]) == ARGV[1] then\n return redis.call(\"del\", KEYS[1])\n else\n return 0\n end\n `;\n\t\treturn this.redisService.redisClient.eval(lua, 1, lockKey, token);\n\t}\n\n\tprivate async logApiUsage(\n\t\tendpoint: string,\n\t\tcacheHit = false,\n\t\tmetadata: {\n\t\t\torigin?: ICoordinate;\n\t\t\tdestination?: ICoordinate;\n\t\t\twaypoints?: ICoordinate[];\n\t\t\tipAddress?: string;\n\t\t\tuserAgent?: string;\n\t\t} = {},\n\t\tresponseTime: number,\n\t\terror?: Error\n\t) {\n\t\ttry {\n\t\t\tawait this.logModel.create({\n\t\t\t\tendpoint,\n\t\t\t\tcacheHit,\n\t\t\t\terror: error ? error.message : null,\n\t\t\t\tresponseTime: responseTime,\n\t\t\t\tmetadata: {\n\t\t\t\t\torigin: metadata.origin || null,\n\t\t\t\t\tdestination: metadata.destination || null,\n\t\t\t\t\twaypoints: metadata.waypoints || null,\n\t\t\t\t\tipAddress: metadata.ipAddress || null,\n\t\t\t\t\tuserAgent: metadata.userAgent || null,\n\t\t\t\t},\n\t\t\t});\n\t\t} catch (logError) {\n\t\t\tconsole.error('Failed to log API usage:', logError);\n\t\t}\n\t}\n\n\tprivate clearRouteCache = async (origin: ICoordinate, destination: ICoordinate, waypoints = []) => {\n\t\tconst cacheKey = waypoints\n\t\t\t? `distance_waypoints:${this.createCacheKey(origin, destination, waypoints)}`\n\t\t\t: `distance:${this.createCacheKey(origin, destination)}`;\n\n\t\treturn await this.redisService.deleteCachedObject(cacheKey);\n\t};\n\n\tprivate getCacheStats = async () => {\n\t\tconst keys = await this.redisService.redisClient.keys('distance*');\n\t\treturn {\n\t\t\ttotalCachedRoutes: keys.length,\n\t\t\tcacheKeys: keys,\n\t\t};\n\t};\n\n\tpublic async getDistanceInfo(origin: ICoordinate, destination: ICoordinate): Promise<IDistanceInfo> {\n\t\tconst startTime = Date.now();\n\t\tconst cacheKey = `distance:${this.createCacheKey(origin, destination)}`;\n\t\tconst cacheTTL = 3600;\n\n\t\ttry {\n\t\t\tconst cachedData: IDistanceInfo | undefined = await this.redisService.getCachedObject(cacheKey);\n\t\t\tif (cachedData) {\n\t\t\t\tconst responseTime = Date.now() - startTime;\n\t\t\t\tawait this.logApiUsage(\n\t\t\t\t\t'DistanceInfoGoogle',\n\t\t\t\t\ttrue,\n\t\t\t\t\t{\n\t\t\t\t\t\torigin,\n\t\t\t\t\t\tdestination,\n\t\t\t\t\t},\n\t\t\t\t\tresponseTime\n\t\t\t\t);\n\t\t\t\treturn cachedData;\n\t\t\t}\n\n\t\t\tconst lock = await this.acquireDistributedLock(cacheKey);\n\n\t\t\ttry {\n\t\t\t\tconst cachedDataAfterLock: IDistanceInfo | undefined =\n\t\t\t\t\tawait this.redisService.getCachedObject(cacheKey);\n\t\t\t\tif (cachedDataAfterLock) {\n\t\t\t\t\tconst responseTime = Date.now() - startTime;\n\t\t\t\t\tawait this.logApiUsage(\n\t\t\t\t\t\t'DistanceInfoGoogle',\n\t\t\t\t\t\ttrue,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\torigin,\n\t\t\t\t\t\t\tdestination,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tresponseTime\n\t\t\t\t\t);\n\t\t\t\t\treturn cachedDataAfterLock;\n\t\t\t\t}\n\n\t\t\t\tconst result = await this.getDistanceInfoFromGoogle(origin, destination);\n\n\t\t\t\tawait this.redisService.cacheObject(cacheKey, result, cacheTTL);\n\n\t\t\t\tconst responseTime = Date.now() - startTime;\n\t\t\t\tawait this.logApiUsage(\n\t\t\t\t\t'DistanceInfoGoogle',\n\t\t\t\t\tfalse,\n\t\t\t\t\t{\n\t\t\t\t\t\torigin,\n\t\t\t\t\t\tdestination,\n\t\t\t\t\t},\n\t\t\t\t\tresponseTime\n\t\t\t\t);\n\n\t\t\t\treturn result;\n\t\t\t} finally {\n\t\t\t\tif (lock) {\n\t\t\t\t\tawait this.releaseDistributedLock(lock.lockKey, lock.token);\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (error: any) {\n\t\t\tconst responseTime = Date.now() - startTime;\n\t\t\tawait this.logApiUsage(\n\t\t\t\t'DistanceInfoGoogle',\n\t\t\t\tfalse,\n\t\t\t\t{\n\t\t\t\t\torigin,\n\t\t\t\t\tdestination,\n\t\t\t\t},\n\t\t\t\tresponseTime,\n\t\t\t\terror\n\t\t\t);\n\t\t\tthrow new TRPCError({\n\t\t\t\tcode: 'INTERNAL_SERVER_ERROR',\n\t\t\t\tmessage: 'Failed to fetch distance information from Maps API.',\n\t\t\t});\n\t\t}\n\t}\n\n\tprivate async getDistanceInfoFromGoogle(\n\t\torigin: ICoordinate,\n\t\tdestination: ICoordinate\n\t): Promise<IDistanceInfo> {\n\t\ttry {\n\t\t\tconst url = `https://maps.googleapis.com/maps/api/directions/json?origin=${origin.latitude}, ${origin.longitude}&destination=${destination.latitude}, ${destination.longitude}&key=${this._apiKey}&mode=DRIVING`;\n\n\t\t\tconst { data } = await axios.get(url);\n\n\t\t\tconst legs = data?.routes[0]?.legs[0];\n\n\t\t\tconst distance = legs?.distance;\n\t\t\tconst duration = legs?.duration;\n\n\t\t\tif (!distance || !duration) {\n\t\t\t\tthrow new TRPCError({\n\t\t\t\t\tcode: 'INTERNAL_SERVER_ERROR',\n\t\t\t\t\tmessage: 'No path exists from origin to destination.',\n\t\t\t\t});\n\t\t\t}\n\n\t\t\treturn { distance, duration };\n\t\t} catch (error) {\n\t\t\tconsole.error(`Error in getDistanceInfo: ${error}`);\n\t\t\tthrow new TRPCError({\n\t\t\t\tcode: 'INTERNAL_SERVER_ERROR',\n\t\t\t\tmessage: 'Failed to fetch distance information from Google Maps API.',\n\t\t\t});\n\t\t}\n\t}\n\n\tpublic async getWaypointsDistanceInfo(\n\t\torigin: ICoordinate,\n\t\tdestination: ICoordinate,\n\t\twaypoints: Array<ICoordinate>\n\t): Promise<IWaypointDistanceInfo> {\n\t\tconst startTime = Date.now();\n\t\tconst cacheKey = `distance_waypoints:${this.createCacheKey(origin, destination, waypoints)}`;\n\t\tconst cacheTTL = 3600;\n\n\t\ttry {\n\t\t\tconst cachedData: IWaypointDistanceInfo | undefined = await this.redisService.getCachedObject(cacheKey);\n\t\t\tif (cachedData) {\n\t\t\t\tconst responseTime = Date.now() - startTime;\n\t\t\t\tawait this.logApiUsage(\n\t\t\t\t\t'DistanceInfoGoogleWithWayPoints',\n\t\t\t\t\ttrue,\n\t\t\t\t\t{\n\t\t\t\t\t\torigin,\n\t\t\t\t\t\tdestination,\n\t\t\t\t\t\twaypoints,\n\t\t\t\t\t},\n\t\t\t\t\tresponseTime\n\t\t\t\t);\n\t\t\t\treturn cachedData;\n\t\t\t}\n\n\t\t\tconst lock = await this.acquireDistributedLock(cacheKey);\n\n\t\t\ttry {\n\t\t\t\tconst cachedDataAfterLock: IWaypointDistanceInfo | undefined =\n\t\t\t\t\tawait this.redisService.getCachedObject(cacheKey);\n\t\t\t\tif (cachedDataAfterLock) {\n\t\t\t\t\tconst responseTime = Date.now() - startTime;\n\t\t\t\t\tawait this.logApiUsage(\n\t\t\t\t\t\t'DistanceInfoGoogleWithWayPoints',\n\t\t\t\t\t\ttrue,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\torigin,\n\t\t\t\t\t\t\tdestination,\n\t\t\t\t\t\t\twaypoints,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tresponseTime\n\t\t\t\t\t);\n\t\t\t\t\treturn cachedDataAfterLock;\n\t\t\t\t}\n\n\t\t\t\tconst result = await this.getWaypointsDistanceInfoFromGoogle(origin, destination, waypoints);\n\n\t\t\t\tawait this.redisService.cacheObject(cacheKey, result, cacheTTL);\n\n\t\t\t\tconst responseTime = Date.now() - startTime;\n\t\t\t\tawait this.logApiUsage(\n\t\t\t\t\t'DistanceInfoGoogleWithWayPoints',\n\t\t\t\t\tfalse,\n\t\t\t\t\t{\n\t\t\t\t\t\torigin,\n\t\t\t\t\t\tdestination,\n\t\t\t\t\t\twaypoints,\n\t\t\t\t\t},\n\t\t\t\t\tresponseTime\n\t\t\t\t);\n\n\t\t\t\treturn result;\n\t\t\t} finally {\n\t\t\t\tif (lock) {\n\t\t\t\t\tawait this.releaseDistributedLock(lock.lockKey, lock.token);\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (error: any) {\n\t\t\tconst responseTime = Date.now() - startTime;\n\t\t\tawait this.logApiUsage(\n\t\t\t\t'DistanceInfoGoogleWithWayPoints',\n\t\t\t\tfalse,\n\t\t\t\t{\n\t\t\t\t\torigin,\n\t\t\t\t\tdestination,\n\t\t\t\t\twaypoints,\n\t\t\t\t},\n\t\t\t\tresponseTime,\n\t\t\t\terror\n\t\t\t);\n\t\t\tthrow new TRPCError({\n\t\t\t\tcode: 'INTERNAL_SERVER_ERROR',\n\t\t\t\tmessage: 'Failed to fetch waypoint distance information from Maps API.',\n\t\t\t});\n\t\t}\n\t}\n\n\tprivate async getWaypointsDistanceInfoFromGoogle(\n\t\torigin: ICoordinate,\n\t\tdestination: ICoordinate,\n\t\twaypoints: Array<ICoordinate>\n\t): Promise<IWaypointDistanceInfo> {\n\t\ttry {\n\t\t\tconst waypointsStr = waypoints.map(point => `${point.latitude},${point.longitude}`).join('|');\n\n\t\t\tconst url = `https://maps.googleapis.com/maps/api/directions/json?origin=${origin.latitude},${origin.longitude}&destination=${destination.latitude},${destination.longitude}&waypoints=${waypointsStr}&key=${this._apiKey}&mode=DRIVING`;\n\n\t\t\tconst { data } = await axios.get(url);\n\n\t\t\tconst routes = data?.routes[0];\n\n\t\t\tconst overviewPolyline = polyline.decode(routes?.overview_polyline?.points);\n\n\t\t\tconst legs = (routes?.legs ?? []).map((leg: { steps: any[]; distance: any; duration: any }) => {\n\t\t\t\tconst overviewPolyline = leg?.steps?.flatMap(step => polyline.decode(step?.polyline?.points));\n\n\t\t\t\treturn {\n\t\t\t\t\tdistance: leg.distance,\n\t\t\t\t\tduration: leg.duration,\n\t\t\t\t\toverviewPolyline,\n\t\t\t\t};\n\t\t\t});\n\n\t\t\tconst totalDistance = legs?.reduce(\n\t\t\t\t(acc: any, curr: { distance: { value: any } }) => acc + curr.distance.value,\n\t\t\t\t0\n\t\t\t);\n\t\t\tconst distance = {\n\t\t\t\ttext: `${(totalDistance / 1000).toFixed(2)} km`,\n\t\t\t\tvalue: totalDistance,\n\t\t\t};\n\n\t\t\tconst totalDuration = legs?.reduce(\n\t\t\t\t(acc: any, curr: { duration: { value: any } }) => acc + curr.duration.value,\n\t\t\t\t0\n\t\t\t);\n\t\t\tconst duration = {\n\t\t\t\ttext: `${Math.round(totalDuration / 60)} mins`,\n\t\t\t\tvalue: totalDuration,\n\t\t\t};\n\n\t\t\tif (!distance || !duration) {\n\t\t\t\tthrow new TRPCError({\n\t\t\t\t\tcode: 'INTERNAL_SERVER_ERROR',\n\t\t\t\t\tmessage: 'No path exists from origin to destination.',\n\t\t\t\t});\n\t\t\t}\n\n\t\t\treturn { distance, duration, legs, overviewPolyline };\n\t\t} catch (error) {\n\t\t\tconsole.error(`Error in getWaypointsDistanceInfo: ${error}`);\n\t\t\tthrow new TRPCError({\n\t\t\t\tcode: 'INTERNAL_SERVER_ERROR',\n\t\t\t\tmessage: 'Failed to fetch waypoint distance information from Google Maps API.',\n\t\t\t});\n\t\t}\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"google-maps.js","sourceRoot":"/","sources":["libraries/map/providers/google-maps.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,kDAA0B;AAW1B,2DAA6C;AAC7C,yCAAyC;AACzC,uCAA2C;AAC3C,mCAAiD;AACjD,mCAAgC;AAChC,+CAA0D;AAU1D,IAAa,iBAAiB,GAA9B,MAAa,iBAAiB;IAOQ;IAN7B,OAAO,CAAqB;IAC5B,QAAQ,CAA8B;IACtC,SAAS,GAAW,2DAA2D,CAAC;IAChF,eAAe,GAAW,oEAAoE,CAAC;IAEvG,YACqC,YAA0B,EAC9D,MAAc;QADsB,iBAAY,GAAZ,YAAY,CAAc;QAG9D,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC;QACtB,IAAI,CAAC,QAAQ,GAAG,6BAAmD,CAAC;IACrE,CAAC;IAEO,cAAc,CAAC,MAAmB,EAAE,WAAwB,EAAE,YAA2B,EAAE;QAClG,MAAM,SAAS,GAAG,GAAG,MAAM,CAAC,QAAQ,IAAI,MAAM,CAAC,SAAS,EAAE,CAAC;QAC3D,MAAM,cAAc,GAAG,GAAG,WAAW,CAAC,QAAQ,IAAI,WAA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,GAAG,GAAG,CAAC,cAAc,GAAG,IAAI,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,KAAK,CAAC;QAEhE,OAAO,EAAE,KAAK,EAAE,aAAa,EAAE,IAAI,EAAE,YAAY,EAAE,CAAC;IACrD,CAAC;CACD,CAAA;AA9jBY,8CAAiB;4BAAjB,iBAAiB;IAO3B,WAAA,IAAA,eAAM,EAAC,GAAG,EAAE,CAAC,oBAAY,CAAC,CAAA;qCAAuB,oBAAY;GAPnD,iBAAiB,CA8jB7B","sourcesContent":["import axios from 'axios';\nimport {\n\tIMapService,\n\tICoordinate,\n\tIDistance,\n\tIDuration,\n\tILeg,\n\tIDistanceInfo,\n\tIWaypointDistanceInfo,\n\tIRouteMatrixDTO,\n} from '../interfaces/IMapService';\nimport * as polyline from '@mapbox/polyline';\nimport { TRPCError } from '@trpc/server';\nimport { RedisService } from '../../redis';\nimport { createHash, randomBytes } from 'crypto';\nimport { Inject } from 'typedi';\nimport { GoogleMapsUsageModel } from '../../mongo/models';\n\ninterface RouteMatrixItem {\n\toriginIndex: number;\n\tdestinationIndex: number;\n\tdistanceMeters?: number;\n\tduration?: string;\n\tcondition: string;\n}\n\nexport class GoogleMapsService implements IMapService {\n\tprivate _apiKey: string | undefined;\n\tprivate logModel: typeof GoogleMapsUsageModel;\n\tprivate _routeURL: string = 'https://routes.googleapis.com/directions/v2:computeRoutes';\n\tprivate _routeMatrixURL: string = 'https://routes.googleapis.com/distanceMatrix/v2:computeRouteMatrix';\n\n\tconstructor(\n\t\t@Inject(() => RedisService) private redisService: RedisService,\n\t\tapiKey: string\n\t) {\n\t\tthis._apiKey = apiKey;\n\t\tthis.logModel = GoogleMapsUsageModel as typeof GoogleMapsUsageModel;\n\t}\n\n\tprivate createCacheKey(origin: ICoordinate, destination: ICoordinate, waypoints: ICoordinate[] = []) {\n\t\tconst originKey = `${origin.latitude},${origin.longitude}`;\n\t\tconst destinationKey = `${destination.latitude},${destination.longitude}`;\n\n\t\tlet keyData = { origin: originKey, destination: destinationKey, waypoints: [] as string[] };\n\n\t\tif (waypoints && waypoints.length > 0) {\n\t\t\tkeyData.waypoints = waypoints.map(point => `${point.latitude},${point.longitude}`).sort();\n\t\t}\n\n\t\treturn createHash('md5').update(JSON.stringify(keyData)).digest('hex');\n\t}\n\n\tprivate async acquireDistributedLock(key: string, ttl = 10) {\n\t\tconst token = randomBytes(16).toString('hex');\n\t\tconst lockKey = `lock:${key}`;\n\n\t\tconst result = await this.redisService.redisClient.set(lockKey, token, 'EX', ttl, 'NX');\n\t\treturn result ? { token, lockKey } : null;\n\t}\n\n\tprivate async releaseDistributedLock(lockKey: string, token: string) {\n\t\tconst lua = `\n if redis.call(\"get\", KEYS[1]) == ARGV[1] then\n return redis.call(\"del\", KEYS[1])\n else\n return 0\n end\n `;\n\t\treturn this.redisService.redisClient.eval(lua, 1, lockKey, token);\n\t}\n\n\tprivate async logApiUsage(\n\t\tendpoint: string,\n\t\tcacheHit = false,\n\t\tmetadata: {\n\t\t\torigin?: ICoordinate;\n\t\t\tdestination?: ICoordinate;\n\t\t\twaypoints?: ICoordinate[];\n\t\t\tipAddress?: string;\n\t\t\tuserAgent?: string;\n\t\t} = {},\n\t\tresponseTime: number,\n\t\terror?: Error\n\t) {\n\t\ttry {\n\t\t\tawait this.logModel.create({\n\t\t\t\tendpoint,\n\t\t\t\tcacheHit,\n\t\t\t\terror: error ? error.message : null,\n\t\t\t\tresponseTime: responseTime,\n\t\t\t\tmetadata: {\n\t\t\t\t\torigin: metadata.origin || null,\n\t\t\t\t\tdestination: metadata.destination || null,\n\t\t\t\t\twaypoints: metadata.waypoints || null,\n\t\t\t\t\tipAddress: metadata.ipAddress || null,\n\t\t\t\t\tuserAgent: metadata.userAgent || null,\n\t\t\t\t},\n\t\t\t});\n\t\t} catch (logError) {\n\t\t\tconsole.error('Failed to log API usage:', logError);\n\t\t}\n\t}\n\n\tprivate clearRouteCache = async (origin: ICoordinate, destination: ICoordinate, waypoints = []) => {\n\t\tconst cacheKey = waypoints\n\t\t\t? `distance_waypoints:${this.createCacheKey(origin, destination, waypoints)}`\n\t\t\t: `distance:${this.createCacheKey(origin, destination)}`;\n\n\t\treturn await this.redisService.deleteCachedObject(cacheKey);\n\t};\n\n\tprivate getCacheStats = async () => {\n\t\tconst keys = await this.redisService.redisClient.keys('distance*');\n\t\treturn {\n\t\t\ttotalCachedRoutes: keys.length,\n\t\t\tcacheKeys: keys,\n\t\t};\n\t};\n\n\tpublic async getDistanceInfo(origin: ICoordinate, destination: ICoordinate): Promise<IDistanceInfo> {\n\t\tconst startTime = Date.now();\n\t\tconst cacheKey = `distance:${this.createCacheKey(origin, destination)}`;\n\t\tconst cacheTTL = 3600;\n\n\t\ttry {\n\t\t\tconst cachedData: IDistanceInfo | undefined = await this.redisService.getCachedObject(cacheKey);\n\t\t\tif (cachedData) {\n\t\t\t\tconst responseTime = Date.now() - startTime;\n\t\t\t\tawait this.logApiUsage(\n\t\t\t\t\t'DistanceInfoGoogle',\n\t\t\t\t\ttrue,\n\t\t\t\t\t{\n\t\t\t\t\t\torigin,\n\t\t\t\t\t\tdestination,\n\t\t\t\t\t},\n\t\t\t\t\tresponseTime\n\t\t\t\t);\n\t\t\t\treturn cachedData;\n\t\t\t}\n\n\t\t\tconst lock = await this.acquireDistributedLock(cacheKey);\n\n\t\t\ttry {\n\t\t\t\tconst cachedDataAfterLock: IDistanceInfo | undefined =\n\t\t\t\t\tawait this.redisService.getCachedObject(cacheKey);\n\t\t\t\tif (cachedDataAfterLock) {\n\t\t\t\t\tconst responseTime = Date.now() - startTime;\n\t\t\t\t\tawait this.logApiUsage(\n\t\t\t\t\t\t'DistanceInfoGoogle',\n\t\t\t\t\t\ttrue,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\torigin,\n\t\t\t\t\t\t\tdestination,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tresponseTime\n\t\t\t\t\t);\n\t\t\t\t\treturn cachedDataAfterLock;\n\t\t\t\t}\n\n\t\t\t\tconst result = await this.getDistanceInfoFromGoogle(origin, destination);\n\n\t\t\t\tawait this.redisService.cacheObject(cacheKey, result, cacheTTL);\n\n\t\t\t\tconst responseTime = Date.now() - startTime;\n\t\t\t\tawait this.logApiUsage(\n\t\t\t\t\t'DistanceInfoGoogle',\n\t\t\t\t\tfalse,\n\t\t\t\t\t{\n\t\t\t\t\t\torigin,\n\t\t\t\t\t\tdestination,\n\t\t\t\t\t},\n\t\t\t\t\tresponseTime\n\t\t\t\t);\n\n\t\t\t\treturn result;\n\t\t\t} finally {\n\t\t\t\tif (lock) {\n\t\t\t\t\tawait this.releaseDistributedLock(lock.lockKey, lock.token);\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (error: any) {\n\t\t\tconst responseTime = Date.now() - startTime;\n\t\t\tawait this.logApiUsage(\n\t\t\t\t'DistanceInfoGoogle',\n\t\t\t\tfalse,\n\t\t\t\t{\n\t\t\t\t\torigin,\n\t\t\t\t\tdestination,\n\t\t\t\t},\n\t\t\t\tresponseTime,\n\t\t\t\terror\n\t\t\t);\n\t\t\tthrow new TRPCError({\n\t\t\t\tcode: 'INTERNAL_SERVER_ERROR',\n\t\t\t\tmessage: 'Failed to fetch distance information from Maps API.',\n\t\t\t});\n\t\t}\n\t}\n\n\tprivate async getDistanceInfoFromGoogle_DEPRECATED(\n\t\torigin: ICoordinate,\n\t\tdestination: ICoordinate\n\t): Promise<IDistanceInfo> {\n\t\ttry {\n\t\t\tconst url = `https://maps.googleapis.com/maps/api/directions/json?origin=${origin.latitude}, ${origin.longitude}&destination=${destination.latitude}, ${destination.longitude}&key=${this._apiKey}&mode=DRIVING`;\n\n\t\t\tconst { data } = await axios.get(url);\n\n\t\t\tconst legs = data?.routes[0]?.legs[0];\n\n\t\t\tconst distance = legs?.distance;\n\t\t\tconst duration = legs?.duration;\n\n\t\t\tif (!distance || !duration) {\n\t\t\t\tthrow new TRPCError({\n\t\t\t\t\tcode: 'INTERNAL_SERVER_ERROR',\n\t\t\t\t\tmessage: 'No path exists from origin to destination.',\n\t\t\t\t});\n\t\t\t}\n\n\t\t\treturn { distance, duration };\n\t\t} catch (error) {\n\t\t\tconsole.error(`Error in getDistanceInfo: ${error}`);\n\t\t\tthrow new TRPCError({\n\t\t\t\tcode: 'INTERNAL_SERVER_ERROR',\n\t\t\t\tmessage: 'Failed to fetch distance information from Google Maps API.',\n\t\t\t});\n\t\t}\n\t}\n\n\tpublic async getWaypointsDistanceInfo(\n\t\torigin: ICoordinate,\n\t\tdestination: ICoordinate,\n\t\twaypoints: Array<ICoordinate>\n\t): Promise<IWaypointDistanceInfo> {\n\t\tconst startTime = Date.now();\n\t\tconst cacheKey = `distance_waypoints:${this.createCacheKey(origin, destination, waypoints)}`;\n\t\tconst cacheTTL = 3600;\n\n\t\ttry {\n\t\t\tconst cachedData: IWaypointDistanceInfo | undefined = await this.redisService.getCachedObject(cacheKey);\n\t\t\tif (cachedData) {\n\t\t\t\tconst responseTime = Date.now() - startTime;\n\t\t\t\tawait this.logApiUsage(\n\t\t\t\t\t'DistanceInfoGoogleWithWayPoints',\n\t\t\t\t\ttrue,\n\t\t\t\t\t{\n\t\t\t\t\t\torigin,\n\t\t\t\t\t\tdestination,\n\t\t\t\t\t\twaypoints,\n\t\t\t\t\t},\n\t\t\t\t\tresponseTime\n\t\t\t\t);\n\t\t\t\treturn cachedData;\n\t\t\t}\n\n\t\t\tconst lock = await this.acquireDistributedLock(cacheKey);\n\n\t\t\ttry {\n\t\t\t\tconst cachedDataAfterLock: IWaypointDistanceInfo | undefined =\n\t\t\t\t\tawait this.redisService.getCachedObject(cacheKey);\n\t\t\t\tif (cachedDataAfterLock) {\n\t\t\t\t\tconst responseTime = Date.now() - startTime;\n\t\t\t\t\tawait this.logApiUsage(\n\t\t\t\t\t\t'DistanceInfoGoogleWithWayPoints',\n\t\t\t\t\t\ttrue,\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\torigin,\n\t\t\t\t\t\t\tdestination,\n\t\t\t\t\t\t\twaypoints,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tresponseTime\n\t\t\t\t\t);\n\t\t\t\t\treturn cachedDataAfterLock;\n\t\t\t\t}\n\n\t\t\t\tconst result = await this.getWaypointsDistanceInfoFromGoogle(origin, destination, waypoints);\n\n\t\t\t\tawait this.redisService.cacheObject(cacheKey, result, cacheTTL);\n\n\t\t\t\tconst responseTime = Date.now() - startTime;\n\t\t\t\tawait this.logApiUsage(\n\t\t\t\t\t'DistanceInfoGoogleWithWayPoints',\n\t\t\t\t\tfalse,\n\t\t\t\t\t{\n\t\t\t\t\t\torigin,\n\t\t\t\t\t\tdestination,\n\t\t\t\t\t\twaypoints,\n\t\t\t\t\t},\n\t\t\t\t\tresponseTime\n\t\t\t\t);\n\n\t\t\t\treturn result;\n\t\t\t} finally {\n\t\t\t\tif (lock) {\n\t\t\t\t\tawait this.releaseDistributedLock(lock.lockKey, lock.token);\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (error: any) {\n\t\t\tconst responseTime = Date.now() - startTime;\n\t\t\tawait this.logApiUsage(\n\t\t\t\t'DistanceInfoGoogleWithWayPoints',\n\t\t\t\tfalse,\n\t\t\t\t{\n\t\t\t\t\torigin,\n\t\t\t\t\tdestination,\n\t\t\t\t\twaypoints,\n\t\t\t\t},\n\t\t\t\tresponseTime,\n\t\t\t\terror\n\t\t\t);\n\t\t\tthrow new TRPCError({\n\t\t\t\tcode: 'INTERNAL_SERVER_ERROR',\n\t\t\t\tmessage: 'Failed to fetch waypoint distance information from Maps API.',\n\t\t\t});\n\t\t}\n\t}\n\n\tprivate async getWaypointsDistanceInfoFromGoogle_DEPRECATED(\n\t\torigin: ICoordinate,\n\t\tdestination: ICoordinate,\n\t\twaypoints: Array<ICoordinate>\n\t): Promise<IWaypointDistanceInfo> {\n\t\ttry {\n\t\t\tconst waypointsStr = waypoints.map(point => `${point.latitude},${point.longitude}`).join('|');\n\n\t\t\tconst url = `https://maps.googleapis.com/maps/api/directions/json?origin=${origin.latitude},${origin.longitude}&destination=${destination.latitude},${destination.longitude}&waypoints=${waypointsStr}&key=${this._apiKey}&mode=DRIVING`;\n\n\t\t\tconst { data } = await axios.get(url);\n\n\t\t\tconst routes = data?.routes[0];\n\n\t\t\tconst overviewPolyline = polyline.decode(routes?.overview_polyline?.points);\n\n\t\t\tconst legs = (routes?.legs ?? []).map((leg: { steps: any[]; distance: any; duration: any }) => {\n\t\t\t\tconst overviewPolyline = leg?.steps?.flatMap(step => polyline.decode(step?.polyline?.points));\n\n\t\t\t\treturn {\n\t\t\t\t\tdistance: leg.distance,\n\t\t\t\t\tduration: leg.duration,\n\t\t\t\t\toverviewPolyline,\n\t\t\t\t};\n\t\t\t});\n\n\t\t\tconst totalDistance = legs?.reduce(\n\t\t\t\t(acc: any, curr: { distance: { value: any } }) => acc + curr.distance.value,\n\t\t\t\t0\n\t\t\t);\n\t\t\tconst distance = {\n\t\t\t\ttext: `${(totalDistance / 1000).toFixed(2)} km`,\n\t\t\t\tvalue: totalDistance,\n\t\t\t};\n\n\t\t\tconst totalDuration = legs?.reduce(\n\t\t\t\t(acc: any, curr: { duration: { value: any } }) => acc + curr.duration.value,\n\t\t\t\t0\n\t\t\t);\n\t\t\tconst duration = {\n\t\t\t\ttext: `${Math.round(totalDuration / 60)} mins`,\n\t\t\t\tvalue: totalDuration,\n\t\t\t};\n\n\t\t\tif (!distance || !duration) {\n\t\t\t\tthrow new TRPCError({\n\t\t\t\t\tcode: 'INTERNAL_SERVER_ERROR',\n\t\t\t\t\tmessage: 'No path exists from origin to destination.',\n\t\t\t\t});\n\t\t\t}\n\n\t\t\treturn { distance, duration, legs, overviewPolyline };\n\t\t} catch (error) {\n\t\t\tconsole.error(`Error in getWaypointsDistanceInfo: ${error}`);\n\t\t\tthrow new TRPCError({\n\t\t\t\tcode: 'INTERNAL_SERVER_ERROR',\n\t\t\t\tmessage: 'Failed to fetch waypoint distance information from Google Maps API.',\n\t\t\t});\n\t\t}\n\t}\n\n\tpublic async getDistanceMatrix(\n\t\torigins: Array<ICoordinate>,\n\t\tdestinations: Array<ICoordinate>\n\t): Promise<IRouteMatrixDTO[]> {\n\t\ttry {\n\t\t\tconst body = {\n\t\t\t\torigins: origins.map(this.toWaypoint),\n\t\t\t\tdestinations: destinations.map(this.toWaypoint),\n\t\t\t\ttravelMode: 'DRIVE',\n\t\t\t\troutingPreference: 'TRAFFIC_AWARE',\n\t\t\t};\n\n\t\t\tconst fieldMask = 'originIndex,destinationIndex,duration,distanceMeters,condition';\n\n\t\t\tconst response = await axios.post(this._routeMatrixURL, body, {\n\t\t\t\theaders: {\n\t\t\t\t\t'Content-Type': 'application/json',\n\t\t\t\t\t'X-Goog-Api-Key': this._apiKey,\n\t\t\t\t\t'X-Goog-FieldMask': fieldMask,\n\t\t\t\t},\n\t\t\t});\n\n\t\t\t// The API returns an array of route elements\n\t\t\tconst results: IRouteMatrixDTO[] = response.data.map((item: RouteMatrixItem) => {\n\t\t\t\tconst distance = this.toDistanceDTO(item.distanceMeters ?? 0);\n\t\t\t\tconst duration = this.toDurationDTO(item.duration ?? '0s');\n\n\t\t\t\treturn {\n\t\t\t\t\tdistance,\n\t\t\t\t\tduration,\n\t\t\t\t\tcondition: item.condition,\n\t\t\t\t\toriginIndex: item.originIndex,\n\t\t\t\t\tdestinationIndex: item.destinationIndex,\n\t\t\t\t};\n\t\t\t});\n\n\t\t\treturn results;\n\t\t} catch (error) {\n\t\t\tconsole.error(`Error in getDistanceMatrix: ${error}`);\n\t\t}\n\n\t\treturn [];\n\t}\n\n\tprivate async getDistanceInfoFromGoogle(origin: ICoordinate, destination: ICoordinate): Promise<IDistanceInfo> {\n\t\ttry {\n\t\t\tconst body = {\n\t\t\t\torigin: this.toLocation(origin),\n\t\t\t\tdestination: this.toLocation(destination),\n\t\t\t\ttravelMode: 'DRIVE',\n\t\t\t\troutingPreference: 'TRAFFIC_AWARE',\n\t\t\t\tcomputeAlternativeRoutes: false,\n\t\t\t\trouteModifiers: {\n\t\t\t\t\tavoidTolls: false,\n\t\t\t\t\tavoidHighways: false,\n\t\t\t\t\tavoidFerries: false,\n\t\t\t\t},\n\t\t\t\tlanguageCode: 'en-US',\n\t\t\t\tunits: 'METRIC',\n\t\t\t};\n\n\t\t\tconsole.log('Request body for getDistanceInfo V2:', body);\n\n\t\t\tconst fieldMask = 'routes.duration,routes.distanceMeters';\n\n\t\t\tconst response = await axios.post(this._routeURL, body, {\n\t\t\t\theaders: {\n\t\t\t\t\t'Content-Type': 'application/json',\n\t\t\t\t\t'X-Goog-Api-Key': this._apiKey,\n\t\t\t\t\t'X-Goog-FieldMask': fieldMask,\n\t\t\t\t},\n\t\t\t});\n\n\t\t\tconsole.log('Response from getDistanceInfo V2:', response.data);\n\n\t\t\tconst route = response.data.routes[0];\n\n\t\t\tconst distance = this.toDistanceDTO(route.distanceMeters);\n\t\t\tconst duration = this.toDurationDTO(route.duration);\n\n\t\t\treturn { distance, duration };\n\t\t} catch (error) {\n\t\t\tconsole.error(`Error in getDistanceInfo V2: ${error}`);\n\t\t\tthrow new TRPCError({\n\t\t\t\tcode: 'INTERNAL_SERVER_ERROR',\n\t\t\t\tmessage: 'Failed to fetch distance information from Google Maps API.',\n\t\t\t});\n\t\t}\n\t}\n\n\tprivate async getWaypointsDistanceInfoFromGoogle(\n\t\torigin: ICoordinate,\n\t\tdestination: ICoordinate,\n\t\twaypoints: Array<ICoordinate>\n\t): Promise<IWaypointDistanceInfo> {\n\t\ttry {\n\t\t\tconst body = {\n\t\t\t\torigin: this.toLocation(origin),\n\t\t\t\tdestination: this.toLocation(destination),\n\t\t\t\tintermediates: waypoints.map(this.toLocation),\n\t\t\t\ttravelMode: 'DRIVE',\n\t\t\t\troutingPreference: 'TRAFFIC_AWARE',\n\t\t\t\tcomputeAlternativeRoutes: false,\n\t\t\t\trouteModifiers: {\n\t\t\t\t\tavoidTolls: false,\n\t\t\t\t\tavoidHighways: false,\n\t\t\t\t\tavoidFerries: false,\n\t\t\t\t},\n\t\t\t\tlanguageCode: 'en-US',\n\t\t\t\tunits: 'METRIC',\n\t\t\t};\n\n\t\t\tconsole.log('Request body for getDistanceInfo V2:', body);\n\n\t\t\tconst fieldMask = 'routes';\n\n\t\t\tconst response = await axios.post(this._routeURL, body, {\n\t\t\t\theaders: {\n\t\t\t\t\t'Content-Type': 'application/json',\n\t\t\t\t\t'X-Goog-Api-Key': this._apiKey,\n\t\t\t\t\t'X-Goog-FieldMask': fieldMask,\n\t\t\t\t},\n\t\t\t});\n\n\t\t\tconsole.log('Response from getWaypointDistanceInfo V2:', JSON.stringify(response.data));\n\n\t\t\tconst route = response.data.routes[0];\n\n\t\t\tconst distance = this.toDistanceDTO(route.distanceMeters);\n\t\t\tconst duration = this.toDurationDTO(route.duration);\n\t\t\tconst overviewPolyline = polyline.decode(route.polyline.encodedPolyline);\n\n\t\t\tconst legs = (route?.legs ?? []).map(\n\t\t\t\t(leg: { polyline: { encodedPolyline: string }; distanceMeters: number; duration: string }) => {\n\t\t\t\t\tconst overviewPolyline = polyline.decode(leg.polyline.encodedPolyline);\n\n\t\t\t\t\tconst legDistance = this.toDistanceDTO(leg.distanceMeters);\n\t\t\t\t\tconst legDuration = this.toDurationDTO(leg.duration);\n\n\t\t\t\t\treturn {\n\t\t\t\t\t\tdistance: legDistance,\n\t\t\t\t\t\tduration: legDuration,\n\t\t\t\t\t\toverviewPolyline,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t);\n\n\t\t\treturn { distance, duration, overviewPolyline, legs };\n\t\t} catch (error) {\n\t\t\tconsole.error(`Error in getWaypointDistanceInfo V2: ${error}`);\n\t\t\tthrow new TRPCError({\n\t\t\t\tcode: 'INTERNAL_SERVER_ERROR',\n\t\t\t\tmessage: 'Failed to fetch waypoint distance information from Google Maps API.',\n\t\t\t});\n\t\t}\n\t}\n\n\t/**\n\t * Converts an ICoordinate to a location object for Google Maps API\n\t * @param coord - ICoordinate object\n\t * @returns Location object for Google Maps API\n\t */\n\tprivate toLocation(coord: ICoordinate) {\n\t\treturn { location: { latLng: { latitude: coord.latitude, longitude: coord.longitude } } };\n\t}\n\n\t/**\n\t * Converts an ICoordinate to a waypoint object for Google Maps API\n\t * @param coord - ICoordinate object\n\t * @returns Waypoint object for Google Maps API\n\t */\n\tprivate toWaypoint(coord: ICoordinate) {\n\t\treturn { waypoint: { location: { latLng: { latitude: coord.latitude, longitude: coord.longitude } } } };\n\t}\n\n\t/**\n\t * Converts a duration string from Google Maps API to an IDuration object\n\t * @param duration in format \"Xs\" where X is number of seconds\n\t * @returns IDuration object\n\t */\n\tprivate toDurationDTO(duration: string): IDuration {\n\t\tconst durationSeconds = parseInt(duration.replace('s', ''));\n\n\t\tconst hours = Math.floor(durationSeconds / 3600);\n\t\tconst minutes = Math.ceil((durationSeconds % 3600) / 60);\n\n\t\tconst durationText = durationSeconds\n\t\t\t? durationSeconds < 60\n\t\t\t\t? `1 min`\n\t\t\t\t: durationSeconds < 3600\n\t\t\t\t\t? minutes === 1\n\t\t\t\t\t\t? '1 min'\n\t\t\t\t\t\t: `${minutes} mins`\n\t\t\t\t\t: hours === 1\n\t\t\t\t\t\t? minutes === 0\n\t\t\t\t\t\t\t? '1 hour'\n\t\t\t\t\t\t\t: minutes === 1\n\t\t\t\t\t\t\t\t? '1 hour 1 min'\n\t\t\t\t\t\t\t\t: `1 hour ${minutes} mins`\n\t\t\t\t\t\t: minutes === 0\n\t\t\t\t\t\t\t? `${hours} hours`\n\t\t\t\t\t\t\t: minutes === 1\n\t\t\t\t\t\t\t\t? `${hours} hours 1 min`\n\t\t\t\t\t\t\t\t: `${hours} hours ${minutes} mins`\n\t\t\t: '1 min';\n\n\t\treturn { value: durationSeconds, text: durationText };\n\t}\n\n\t/**\n\t * Converts a distance in meters from Google Maps API to an IDistance object\n\t * @param distanceMeters distance in meters\n\t * @returns IDistance object\n\t */\n\tprivate toDistanceDTO(distanceMeters: number): IDistance {\n\t\tconst distanceValue = distanceMeters;\n\t\tconst distanceText = `${(distanceMeters / 1000).toFixed(1)} km`;\n\n\t\treturn { value: distanceValue, text: distanceText };\n\t}\n}\n"]}
|
|
@@ -18,7 +18,10 @@ async function subscribeToSocketEvent() {
|
|
|
18
18
|
channel.ack(msg);
|
|
19
19
|
}
|
|
20
20
|
catch (e) {
|
|
21
|
-
console.error('Failed to handle socket event:',
|
|
21
|
+
console.error('[Socket] Failed to handle socket event:', {
|
|
22
|
+
error: e instanceof Error ? e.message : e,
|
|
23
|
+
queue: queueName,
|
|
24
|
+
});
|
|
22
25
|
channel.nack(msg, false, false);
|
|
23
26
|
}
|
|
24
27
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"socket-event-consumer.js","sourceRoot":"/","sources":["libraries/socket/core/socket-event-consumer.ts"],"names":[],"mappings":";;AAIA,
|
|
1
|
+
{"version":3,"file":"socket-event-consumer.js","sourceRoot":"/","sources":["libraries/socket/core/socket-event-consumer.ts"],"names":[],"mappings":";;AAIA,wDAuBC;AA3BD,sEAAkE;AAClE,uCAAwD;AACxD,+EAA0D;AAEnD,KAAK,UAAU,sBAAsB;IAC3C,MAAM,OAAO,GAAG,IAAA,kBAAU,GAAE,CAAC;IAC7B,MAAM,SAAS,GAAG,iBAAiB,IAAA,8BAAa,GAAE,EAAE,CAAC;IAErD,MAAM,OAAO,CAAC,WAAW,CAAC,SAAS,EAAE,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC;IACxD,MAAM,OAAO,CAAC,SAAS,CAAC,SAAS,EAAE,qBAAa,EAAE,YAAY,IAAA,8BAAa,GAAE,EAAE,CAAC,CAAC;IAEjF,MAAM,OAAO,CAAC,OAAO,CAAC,SAAS,EAAE,GAAG,CAAC,EAAE;QACtC,IAAI,CAAC,GAAG;YAAE,OAAO;QACjB,IAAI,CAAC;YACJ,MAAM,EAAE,QAAQ,EAAE,OAAO,EAAE,SAAS,EAAE,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC;YAClF,uCAAS,CAAC,IAAI,CAAC,SAAS,EAAE,QAAQ,EAAE,OAAO,CAAC,CAAC;YAC7C,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;QAClB,CAAC;QAAC,OAAO,CAAC,EAAE,CAAC;YACZ,OAAO,CAAC,KAAK,CAAC,yCAAyC,EAAE;gBACxD,KAAK,EAAE,CAAC,YAAY,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC;gBACzC,KAAK,EAAE,SAAS;aAChB,CAAC,CAAC;YACH,OAAO,CAAC,IAAI,CAAC,GAAG,EAAE,KAAK,EAAE,KAAK,CAAC,CAAC;QACjC,CAAC;IACF,CAAC,CAAC,CAAC;IAEH,OAAO,CAAC,GAAG,CAAC,yCAAyC,SAAS,GAAG,CAAC,CAAC;AACpE,CAAC","sourcesContent":["import { getInstanceId } from '../../../utilities/instance.utils';\nimport { EXCHANGE_NAME, getChannel } from '../../event';\nimport { LocalSubs } from './local-subscription-registry';\n\nexport async function subscribeToSocketEvent() {\n\tconst channel = getChannel();\n\tconst queueName = `socket-events-${getInstanceId()}`;\n\n\tawait channel.assertQueue(queueName, { durable: true });\n\tawait channel.bindQueue(queueName, EXCHANGE_NAME, `instance.${getInstanceId()}`);\n\n\tawait channel.consume(queueName, msg => {\n\t\tif (!msg) return;\n\t\ttry {\n\t\t\tconst { localKey, payload, recipient } = JSON.parse(msg.content.toString('utf8'));\n\t\t\tLocalSubs.emit(recipient, localKey, payload);\n\t\t\tchannel.ack(msg);\n\t\t} catch (e) {\n\t\t\tconsole.error('[Socket] Failed to handle socket event:', {\n\t\t\t\terror: e instanceof Error ? e.message : e,\n\t\t\t\tqueue: queueName,\n\t\t\t});\n\t\t\tchannel.nack(msg, false, false); // Don't requeue malformed messages\n\t\t}\n\t});\n\n\tconsole.log(`Subscribed to socket events on queue [${queueName}]`);\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { BaseSocketEvent } from '../BaseSocketEvent';
|
|
2
2
|
import { EntitySubscription } from './socket-redis-connections';
|
|
3
|
-
import { NotificationSocketEvent } from '../events
|
|
3
|
+
import { NotificationSocketEvent } from '../events';
|
|
4
4
|
export declare function publishSocketEvent(event: BaseSocketEvent<any, any>, recipients: EntitySubscription[]): Promise<void>;
|
|
5
5
|
export declare function publishNotificationSocketEvent(event: NotificationSocketEvent, recipients: EntitySubscription[]): Promise<void>;
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.publishSocketEvent = publishSocketEvent;
|
|
4
4
|
exports.publishNotificationSocketEvent = publishNotificationSocketEvent;
|
|
5
|
+
const __1 = require("../../..");
|
|
5
6
|
const socket_redis_connections_1 = require("./socket-redis-connections");
|
|
6
7
|
const event_1 = require("../../event");
|
|
7
8
|
const PushNotificationEvent_1 = require("../PushNotificationEvent");
|
|
@@ -34,22 +35,32 @@ async function getActiveSubscribedRecipients(recipients, localKey) {
|
|
|
34
35
|
if (recipients.length === 0) {
|
|
35
36
|
return { subscribed: [], unsubscribed: [] };
|
|
36
37
|
}
|
|
37
|
-
const
|
|
38
|
-
const resultsMap = await (0, socket_redis_connections_1.getEntitySubscriptionInfoBatch)(batchInput);
|
|
38
|
+
const redis = (0, __1.getLibraries)().getRedisService();
|
|
39
39
|
const subscribed = [];
|
|
40
40
|
const unsubscribed = [];
|
|
41
|
-
|
|
42
|
-
const
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
41
|
+
await Promise.all(recipients.map(async (recipient) => {
|
|
42
|
+
const sockets = await redis.getSetMembers((0, socket_redis_connections_1.getEntityEventSocketsKey)(recipient, localKey));
|
|
43
|
+
if (sockets.length > 0) {
|
|
44
|
+
const instanceSet = new Set();
|
|
45
|
+
for (let i = 0; i < sockets.length; i++) {
|
|
46
|
+
try {
|
|
47
|
+
const socketInfo = JSON.parse(sockets[i]);
|
|
48
|
+
instanceSet.add(socketInfo.instanceId);
|
|
49
|
+
}
|
|
50
|
+
catch {
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
if (instanceSet.size > 0) {
|
|
54
|
+
subscribed.push({ recipient, instances: Array.from(instanceSet) });
|
|
55
|
+
}
|
|
56
|
+
else {
|
|
57
|
+
unsubscribed.push(recipient);
|
|
58
|
+
}
|
|
48
59
|
}
|
|
49
60
|
else {
|
|
50
61
|
unsubscribed.push(recipient);
|
|
51
62
|
}
|
|
52
|
-
}
|
|
63
|
+
}));
|
|
53
64
|
return { subscribed, unsubscribed };
|
|
54
65
|
}
|
|
55
66
|
async function publishSocketEvent(event, recipients) {
|
|
@@ -76,18 +87,25 @@ async function publishNotificationSocketEvent(event, recipients) {
|
|
|
76
87
|
if (recipients.length === 0)
|
|
77
88
|
return;
|
|
78
89
|
const eventKey = event.getSubscriptionKey();
|
|
79
|
-
const
|
|
80
|
-
const resultsMap = await (0, socket_redis_connections_1.getEntitySubscriptionInfoBatch)(batchInput);
|
|
90
|
+
const redis = (0, __1.getLibraries)().getRedisService();
|
|
81
91
|
const validInstances = [];
|
|
82
|
-
|
|
83
|
-
const
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
92
|
+
await Promise.all(recipients.map(async (recipient) => {
|
|
93
|
+
const sockets = await redis.getSetMembers((0, socket_redis_connections_1.getEntityEventSocketsKey)(recipient, eventKey));
|
|
94
|
+
if (sockets.length > 0) {
|
|
95
|
+
const instanceSet = new Set();
|
|
96
|
+
for (let i = 0; i < sockets.length; i++) {
|
|
97
|
+
try {
|
|
98
|
+
const socketInfo = JSON.parse(sockets[i]);
|
|
99
|
+
instanceSet.add(socketInfo.instanceId);
|
|
100
|
+
}
|
|
101
|
+
catch {
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
if (instanceSet.size > 0) {
|
|
105
|
+
validInstances.push({ recipient, instances: Array.from(instanceSet) });
|
|
106
|
+
}
|
|
89
107
|
}
|
|
90
|
-
}
|
|
108
|
+
}));
|
|
91
109
|
if (validInstances.length > 0) {
|
|
92
110
|
publishToInstances(validInstances, eventKey, event.payload());
|
|
93
111
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"socket-event-publisher.js","sourceRoot":"/","sources":["libraries/socket/core/socket-event-publisher.ts"],"names":[],"mappings":";;AAoFA,gDAkCC;AAGD,wEA2BC;AAlJD,yEAA2H;AAE3H,uCAA6F;AAC7F,oEAAiE;AACjE,kDAAoE;AAGpE,MAAM,eAAe,GAAG;IACvB,WAAW,EAAE,kBAAkB;IAC/B,UAAU,EAAE,IAAI;CACP,CAAC;AAGX,SAAS,kBAAkB,CAC1B,uBAAsF,EACtF,QAAgB,EAChB,OAAY;IAEZ,IAAI,uBAAuB,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO;IAEjD,MAAM,OAAO,GAAG,IAAA,kBAAU,GAAE,CAAC;IAG7B,MAAM,OAAO,GAAG,EAAE,QAAQ,EAAE,OAAO,EAAE,SAAS,EAAE,IAAW,EAAE,CAAC;IAG9D,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,uBAAuB,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;QACzD,MAAM,EAAE,SAAS,EAAE,SAAS,EAAE,GAAG,uBAAuB,CAAC,CAAC,CAAC,CAAC;QAC5D,OAAO,CAAC,SAAS,GAAG,SAAS,CAAC;QAC9B,MAAM,UAAU,GAAG,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC;QAE3C,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,SAAS,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;YAC3C,MAAM,UAAU,GAAG,GAAG,6BAAqB,IAAI,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC;YAE9D,IAAI,CAAC;gBAEJ,OAAO,CAAC,OAAO,CAAC,qBAAa,EAAE,UAAU,EAAE,MAAM,CAAC,IAA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C/D,CAAC;AACF,CAAC","sourcesContent":["import { getLibraries } from '../../..';\nimport { BaseSocketEvent } from '../BaseSocketEvent';\nimport { EntitySubscription, getEntitySubscriptionInfo, getEntitySubscriptionInfoBatch } from './socket-redis-connections';\nimport { NotificationSocketEvent } from '../events/notification.socket.event';\nimport { EXCHANGE_NAME, getChannel, INSTANCE_ROUTE_PREFIX, publishEvent } from '../../event';\nimport { PushNotificationEvent } from '../PushNotificationEvent';\nimport { PushNotificationEventType } from '../../../utilities/enum';\n\n// Reusable publish options\nconst PUBLISH_OPTIONS = {\n\tcontentType: 'application/json',\n\tpersistent: true,\n} as const;\n\n// Zero-overhead publishing - minimal allocations\nfunction publishToInstances(\n\trecipientsWithInstances: Array<{ recipient: EntitySubscription; instances: string[] }>,\n\tlocalKey: string,\n\tpayload: any\n): void {\n\tif (recipientsWithInstances.length === 0) return;\n\n\tconst channel = getChannel();\n\n\t// Pre-serialize message once\n\tconst message = { localKey, payload, recipient: null as any };\n\t\n\t// Fire-and-forget with minimal overhead\n\tfor (let i = 0; i < recipientsWithInstances.length; i++) {\n\t\tconst { recipient, instances } = recipientsWithInstances[i];\n\t\tmessage.recipient = recipient;\n\t\tconst messageStr = JSON.stringify(message);\n\n\t\tfor (let j = 0; j < instances.length; j++) {\n\t\t\tconst routingKey = `${INSTANCE_ROUTE_PREFIX}.${instances[j]}`;\n\t\t\t\n\t\t\ttry {\n\t\t\t\t// Direct publish - Buffer.from creates minimal overhead\n\t\t\t\tchannel.publish(EXCHANGE_NAME, routingKey, Buffer.from(messageStr, 'utf8'), PUBLISH_OPTIONS);\n\t\t\t} catch (error) {\n\t\t\t\tconsole.error(`[Socket] Publish failed: ${routingKey}`, error);\n\t\t\t}\n\t\t}\n\t}\n}\n\n// Zero-allocation recipient filtering\nasync function getActiveSubscribedRecipients(\n\trecipients: EntitySubscription[],\n\tlocalKey: string\n): Promise<{\n\tsubscribed: Array<{ recipient: EntitySubscription; instances: string[] }>;\n\tunsubscribed: EntitySubscription[];\n}> {\n\tif (recipients.length === 0) {\n\t\treturn { subscribed: [], unsubscribed: [] };\n\t}\n\n\t// Use batch API\n\tconst batchInput = recipients.map(recipient => ({ entity: recipient, eventKey: localKey }));\n\tconst resultsMap = await getEntitySubscriptionInfoBatch(batchInput);\n\n\t// Pre-allocate arrays\n\tconst subscribed: Array<{ recipient: EntitySubscription; instances: string[] }> = [];\n\tconst unsubscribed: EntitySubscription[] = [];\n\n\t// Single pass with minimal allocations\n\tfor (let i = 0; i < recipients.length; i++) {\n\t\tconst recipient = recipients[i];\n\t\tconst entityKeyStr = `${recipient.type ?? 'default'}:${recipient.id}`;\n\t\tconst cacheKey = `${entityKeyStr}:${localKey}`;\n\t\tconst info = resultsMap.get(cacheKey);\n\n\t\tif (info && info.isSubscribed && info.instances.length > 0) {\n\t\t\tsubscribed.push({ recipient, instances: info.instances });\n\t\t} else {\n\t\t\tunsubscribed.push(recipient);\n\t\t}\n\t}\n\n\treturn { subscribed, unsubscribed };\n}\n\n// Minimal overhead publish - early returns, lazy evaluation\nexport async function publishSocketEvent(\n\tevent: BaseSocketEvent<any, any>,\n\trecipients: EntitySubscription[]\n): Promise<void> {\n\tif (recipients.length === 0) return;\n\n\tconst localKey = event.getSubscriptionKey();\n\tconst payload = event.payload();\n\n\tconst { subscribed, unsubscribed } = await getActiveSubscribedRecipients(recipients, localKey);\n\n\t// Fire-and-forget: zero blocking\n\tif (subscribed.length > 0) {\n\t\tpublishToInstances(subscribed, localKey, payload);\n\t}\n\n\t// Lazy fallback evaluation - only if needed\n\tif (unsubscribed.length > 0) {\n\t\tconst notificationEvent = event.notification?.();\n\t\tconst pushNotificationEvent = event.pushNotification?.();\n\n\t\t// Fire without awaiting - true fire-and-forget\n\t\tif (pushNotificationEvent) {\n\t\t\tpublishEvent(new PushNotificationEvent(PushNotificationEventType.CHATROOM_MESSAGE_SEND, payload)).catch(\n\t\t\t\terr => console.error('[Socket] Push failed:', err)\n\t\t\t);\n\t\t}\n\n\t\tif (notificationEvent) {\n\t\t\tpublishNotificationSocketEvent(notificationEvent, unsubscribed).catch(err =>\n\t\t\t\tconsole.error('[Socket] Notification failed:', err)\n\t\t\t);\n\t\t}\n\t}\n}\n\n// Zero-overhead notification publish\nexport async function publishNotificationSocketEvent(\n\tevent: NotificationSocketEvent,\n\trecipients: EntitySubscription[]\n): Promise<void> {\n\tif (recipients.length === 0) return;\n\n\tconst eventKey = event.getSubscriptionKey();\n\tconst batchInput = recipients.map(recipient => ({ entity: recipient, eventKey }));\n\tconst resultsMap = await getEntitySubscriptionInfoBatch(batchInput);\n\n\t// Pre-allocate for valid instances\n\tconst validInstances: Array<{ recipient: EntitySubscription; instances: string[] }> = [];\n\n\tfor (let i = 0; i < recipients.length; i++) {\n\t\tconst recipient = recipients[i];\n\t\tconst entityKeyStr = `${recipient.type ?? 'default'}:${recipient.id}`;\n\t\tconst cacheKey = `${entityKeyStr}:${eventKey}`;\n\t\tconst info = resultsMap.get(cacheKey);\n\n\t\tif (info && info.instances.length > 0) {\n\t\t\tvalidInstances.push({ recipient, instances: info.instances });\n\t\t}\n\t}\n\n\tif (validInstances.length > 0) {\n\t\tpublishToInstances(validInstances, eventKey, event.payload());\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"socket-event-publisher.js","sourceRoot":"/","sources":["libraries/socket/core/socket-event-publisher.ts"],"names":[],"mappings":";;AA6FA,gDAkCC;AAGD,wEAmCC;AArKD,gCAAwC;AAExC,yEAA0F;AAE1F,uCAA6F;AAC7F,oEAAiE;AACjE,kDAAoE;AAGpE,MAAM,eAAe,GAAG;IACvB,WAAW,EAAE,kBAAkB;IAC/B,UAAU,EAAE,IAAI;CACP,CAAC;AAGX,SAAS,kBAAkB,CAC1B,uBAAsF,EACtF,QAAgB,EAChB,OAAY;IAEZ,IAAI,uBAAuB,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO;IAEjD,MAAM,OAAO,GAAG,IAAA,kBAAU,GAAE,CAAC;IAG7B,MAAM,OAAO,GAAG,EA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E,SAAS,EAAE,EAAE;QAClC,MAAM,OAAO,GAAG,MAAM,KAAK,CAAC,aAAa,CAAC,IAAA,mDAAwB,EAAC,SAAS,EAAE,QAAQ,CAAC,CAAC,CAAC;QAEzF,IAAI,OAAO,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YACxB,MAAM,WAAW,GAAG,IAAI,GAAG,EAAU,CAAC;YACtC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;gBACzC,IAAI,CAAC;oBACJ,MAAM,UAAU,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC;oBAC1C,WAAW,CAAC,GAAG,CAAC,UAAU,CAAC,UAAU,CAAC,CAAC;gBACxC,CAAC;gBAAC,MAAM,CAAC;gBAET,CAAC;YACF,CAAC;YACD,IAAI,WAAW,CAAC,IAAI,GAAG,CAAC,EAAE,CAAC;gBAC1B,cAAc,CAAC,IAAI,CAAC,EAAE,SAAS,EAAE,SAAS,EAAE,KAAK,CAAC,IAAI,CAAC,WAAW,CAAC,EAAE,CAAC,CAAC;YACxE,CAAC;QACF,CAAC;IACF,CAAC,CAAC,CACF,CAAC;IAEF,IAAI,cAAc,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QAC/B,kBAAkB,CAAC,cAAc,EAAE,QAAQ,EAAE,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;IAC/D,CAAC;AACF,CAAC","sourcesContent":["import { getLibraries } from '../../..';\nimport { BaseSocketEvent } from '../BaseSocketEvent';\nimport { EntitySubscription, getEntityEventSocketsKey } from './socket-redis-connections';\nimport { NotificationSocketEvent } from '../events';\nimport { EXCHANGE_NAME, getChannel, INSTANCE_ROUTE_PREFIX, publishEvent } from '../../event';\nimport { PushNotificationEvent } from '../PushNotificationEvent';\nimport { PushNotificationEventType } from '../../../utilities/enum';\n\n// Reusable publish options\nconst PUBLISH_OPTIONS = {\n\tcontentType: 'application/json',\n\tpersistent: true,\n} as const;\n\n// Zero-overhead publishing - minimal allocations\nfunction publishToInstances(\n\trecipientsWithInstances: Array<{ recipient: EntitySubscription; instances: string[] }>,\n\tlocalKey: string,\n\tpayload: any\n): void {\n\tif (recipientsWithInstances.length === 0) return;\n\n\tconst channel = getChannel();\n\n\t// Pre-serialize message once\n\tconst message = { localKey, payload, recipient: null as any };\n\t\n\t// Fire-and-forget with minimal overhead\n\tfor (let i = 0; i < recipientsWithInstances.length; i++) {\n\t\tconst { recipient, instances } = recipientsWithInstances[i];\n\t\tmessage.recipient = recipient;\n\t\tconst messageStr = JSON.stringify(message);\n\n\t\tfor (let j = 0; j < instances.length; j++) {\n\t\t\tconst routingKey = `${INSTANCE_ROUTE_PREFIX}.${instances[j]}`;\n\t\t\t\n\t\t\ttry {\n\t\t\t\t// Direct publish - Buffer.from creates minimal overhead\n\t\t\t\tchannel.publish(EXCHANGE_NAME, routingKey, Buffer.from(messageStr, 'utf8'), PUBLISH_OPTIONS);\n\t\t\t} catch (error) {\n\t\t\t\tconsole.error(`[Socket] Publish failed: ${routingKey}`, error);\n\t\t\t}\n\t\t}\n\t}\n}\n\n// Ultra-simple: Direct Redis lookups, no batch/cache/parsing!\nasync function getActiveSubscribedRecipients(\n\trecipients: EntitySubscription[],\n\tlocalKey: string\n): Promise<{\n\tsubscribed: Array<{ recipient: EntitySubscription; instances: string[] }>;\n\tunsubscribed: EntitySubscription[];\n}> {\n\tif (recipients.length === 0) {\n\t\treturn { subscribed: [], unsubscribed: [] };\n\t}\n\n\tconst redis = getLibraries().getRedisService();\n\tconst subscribed: Array<{ recipient: EntitySubscription; instances: string[] }> = [];\n\tconst unsubscribed: EntitySubscription[] = [];\n\n\t// Parallel lookups - one key per recipient\n\tawait Promise.all(\n\t\trecipients.map(async (recipient) => {\n\t\t\tconst sockets = await redis.getSetMembers(getEntityEventSocketsKey(recipient, localKey));\n\t\t\t\n\t\t\tif (sockets.length > 0) {\n\t\t\t\t// Extract instances\n\t\t\t\tconst instanceSet = new Set<string>();\n\t\t\t\tfor (let i = 0; i < sockets.length; i++) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst socketInfo = JSON.parse(sockets[i]);\n\t\t\t\t\t\tinstanceSet.add(socketInfo.instanceId);\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t// Skip malformed socket data\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (instanceSet.size > 0) {\n\t\t\t\t\tsubscribed.push({ recipient, instances: Array.from(instanceSet) });\n\t\t\t\t} else {\n\t\t\t\t\tunsubscribed.push(recipient);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tunsubscribed.push(recipient);\n\t\t\t}\n\t\t})\n\t);\n\n\treturn { subscribed, unsubscribed };\n}\n\n// Minimal overhead publish - early returns, lazy evaluation\nexport async function publishSocketEvent(\n\tevent: BaseSocketEvent<any, any>,\n\trecipients: EntitySubscription[]\n): Promise<void> {\n\tif (recipients.length === 0) return;\n\n\tconst localKey = event.getSubscriptionKey();\n\tconst payload = event.payload();\n\n\tconst { subscribed, unsubscribed } = await getActiveSubscribedRecipients(recipients, localKey);\n\n\t// Fire-and-forget: zero blocking\n\tif (subscribed.length > 0) {\n\t\tpublishToInstances(subscribed, localKey, payload);\n\t}\n\n\t// Lazy fallback evaluation - only if needed\n\tif (unsubscribed.length > 0) {\n\t\tconst notificationEvent = event.notification?.();\n\t\tconst pushNotificationEvent = event.pushNotification?.();\n\n\t\t// Fire without awaiting - true fire-and-forget\n\t\tif (pushNotificationEvent) {\n\t\t\tpublishEvent(new PushNotificationEvent(PushNotificationEventType.CHATROOM_MESSAGE_SEND, payload)).catch(\n\t\t\t\terr => console.error('[Socket] Push failed:', err)\n\t\t\t);\n\t\t}\n\n\t\tif (notificationEvent) {\n\t\t\tpublishNotificationSocketEvent(notificationEvent, unsubscribed).catch(err =>\n\t\t\t\tconsole.error('[Socket] Notification failed:', err)\n\t\t\t);\n\t\t}\n\t}\n}\n\n// Ultra-simple notification publish: Direct lookups!\nexport async function publishNotificationSocketEvent(\n\tevent: NotificationSocketEvent,\n\trecipients: EntitySubscription[]\n): Promise<void> {\n\tif (recipients.length === 0) return;\n\n\tconst eventKey = event.getSubscriptionKey();\n\tconst redis = getLibraries().getRedisService();\n\tconst validInstances: Array<{ recipient: EntitySubscription; instances: string[] }> = [];\n\n\t// Parallel direct lookups\n\tawait Promise.all(\n\t\trecipients.map(async (recipient) => {\n\t\t\tconst sockets = await redis.getSetMembers(getEntityEventSocketsKey(recipient, eventKey));\n\t\t\t\n\t\t\tif (sockets.length > 0) {\n\t\t\t\tconst instanceSet = new Set<string>();\n\t\t\t\tfor (let i = 0; i < sockets.length; i++) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst socketInfo = JSON.parse(sockets[i]);\n\t\t\t\t\t\tinstanceSet.add(socketInfo.instanceId);\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t// Skip malformed socket data\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (instanceSet.size > 0) {\n\t\t\t\t\tvalidInstances.push({ recipient, instances: Array.from(instanceSet) });\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t);\n\n\tif (validInstances.length > 0) {\n\t\tpublishToInstances(validInstances, eventKey, event.payload());\n\t}\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"socket-event-registry.map.js","sourceRoot":"/","sources":["libraries/socket/core/socket-event-registry.map.ts"],"names":[],"mappings":";;;AAAA,kDAA0D;AAC1D,sCAA2F;AAC3F,qFAAyE;AACzE,yFAA6E;AAE7E,mFAA8E;AAC9E,qFAA+E;AAC/E,qGAA8F;
|
|
1
|
+
{"version":3,"file":"socket-event-registry.map.js","sourceRoot":"/","sources":["libraries/socket/core/socket-event-registry.map.ts"],"names":[],"mappings":";;;AAAA,kDAA0D;AAC1D,sCAA2F;AAC3F,qFAAyE;AACzE,yFAA6E;AAE7E,mFAA8E;AAC9E,qFAA+E;AAC/E,qGAA8F;AAEjF,QAAA,QAAQ,GAAG;IACvB,CAAC,sBAAe,CAAC,qBAAqB,CAAC,EAAE;QACxC,IAAI,EAAE,uCAA8B;QACpC,OAAO,EAAE,uCAA8B,CAAC,OAAO;QAC/C,UAAU,EAAE,uCAA8B,CAAC,UAAU;KACrD;IACD,CAAC,sBAAe,CAAC,yBAAyB,CAAC,EAAE;QAC5C,IAAI,EAAE,uCAA8B;QACpC,OAAO,EAAE,uCAA8B,CAAC,OAAO;KAC/C;IACD,CAAC,sBAAe,CAAC,aAAa,CAAC,EAAE;QAChC,IAAI,EAAE,8CAAiB;QACvB,OAAO,EAAE,8CAAiB,CAAC,OAAO;KAClC;IACD,CAAC,sBAAe,CAAC,eAAe,CAAC,EAAE;QAClC,IAAI,EAAE,kDAAmB;QACzB,OAAO,EAAE,kDAAmB,CAAC,OAAO;QACpC,UAAU,EAAE,kDAAmB,CAAC,UAAU;KAC1C;IACD,CAAC,sBAAe,CAAC,YAAY,CAAC,EAAE;QAC/B,IAAI,EAAE,mDAAuB;QAC7B,OAAO,EAAE,mDAAuB,CAAC,OAAO;KACxC;IACD,CAAC,sBAAe,CAAC,aAAa,CAAC,EAAE;QAChC,IAAI,EAAE,oDAAuB;QAC7B,OAAO,EAAE,oDAAuB,CAAC,OAAO;KACxC;IACD,CAAC,sBAAe,CAAC,qBAAqB,CAAC,EAAE;QACxC,IAAI,EAAE,mEAA8B;QACpC,OAAO,EAAE,mEAA8B,CAAC,OAAO;QAC/C,UAAU,EAAE,mEAA8B,CAAC,UAAU;KACrD;CACQ,CAAC","sourcesContent":["import { SocketEventType } from '../../../utilities/enum';\nimport { ChatlistMessageSendSocketEvent, ChatroomMessageSendSocketEvent } from '../events';\nimport { TicketAssignEvent } from '../events/ticket-assign.socket.event';\nimport { TicketUnassignEvent } from '../events/ticket-unassign.socket.event';\nimport { EventRegistration } from './index';\nimport { NotificationSocketEvent } from '../events/notification.socket.event';\nimport { RiderConnectSocketEvent } from '../events/rider-connect.socket.event';\nimport { RiderLocationUpdateSocketEvent } from '../events/rider-location-update.socket.event';\n\nexport const REGISTRY = {\n\t[SocketEventType.CHATROOM_MESSAGE_SEND]: {\n\t\tctor: ChatroomMessageSendSocketEvent,\n\t\tschemas: ChatroomMessageSendSocketEvent.schemas,\n\t\tidentifier: ChatroomMessageSendSocketEvent.identifier,\n\t},\n\t[SocketEventType.CHATLIST_MESSAGE_RECEIVED]: {\n\t\tctor: ChatlistMessageSendSocketEvent,\n\t\tschemas: ChatlistMessageSendSocketEvent.schemas,\n\t},\n\t[SocketEventType.TICKET_ASSIGN]: {\n\t\tctor: TicketAssignEvent,\n\t\tschemas: TicketAssignEvent.schemas,\n\t},\n\t[SocketEventType.TICKET_UNASSIGN]: {\n\t\tctor: TicketUnassignEvent,\n\t\tschemas: TicketUnassignEvent.schemas,\n\t\tidentifier: TicketUnassignEvent.identifier,\n\t},\n\t[SocketEventType.NOTIFICATION]: {\n\t\tctor: NotificationSocketEvent,\n\t\tschemas: NotificationSocketEvent.schemas,\n\t},\n\t[SocketEventType.RIDER_CONNECT]: {\n\t\tctor: RiderConnectSocketEvent,\n\t\tschemas: RiderConnectSocketEvent.schemas,\n\t},\n\t[SocketEventType.RIDER_LOCATION_UPDATE]: {\n\t\tctor: RiderLocationUpdateSocketEvent,\n\t\tschemas: RiderLocationUpdateSocketEvent.schemas,\n\t\tidentifier: RiderLocationUpdateSocketEvent.identifier,\n\t},\n} as const;\n\nexport type Registry = {\n\t[K in keyof typeof REGISTRY]: (typeof REGISTRY)[K] extends EventRegistration<any>\n\t\t? (typeof REGISTRY)[K]\n\t\t: never;\n};\n"]}
|