( request: FastifyRequest, reply: FastifyReply )
| 456 | } |
| 457 | |
| 458 | export async function fetchDeviceId( |
| 459 | request: FastifyRequest, |
| 460 | reply: FastifyReply |
| 461 | ) { |
| 462 | const salts = await getSalts(); |
| 463 | const projectId = request.client?.projectId; |
| 464 | if (!projectId) { |
| 465 | return reply.status(400).send('No projectId'); |
| 466 | } |
| 467 | |
| 468 | const ip = request.clientIp; |
| 469 | if (!ip) { |
| 470 | return reply.status(400).send('Missing ip address'); |
| 471 | } |
| 472 | |
| 473 | const ua = request.headers['user-agent']; |
| 474 | if (!ua) { |
| 475 | return reply.status(400).send('Missing header: user-agent'); |
| 476 | } |
| 477 | |
| 478 | const currentDeviceId = generateDeviceId({ |
| 479 | salt: salts.current, |
| 480 | origin: projectId, |
| 481 | ip, |
| 482 | ua, |
| 483 | }); |
| 484 | const previousDeviceId = generateDeviceId({ |
| 485 | salt: salts.previous, |
| 486 | origin: projectId, |
| 487 | ip, |
| 488 | ua, |
| 489 | }); |
| 490 | |
| 491 | try { |
| 492 | const [current, previous] = await Promise.all([ |
| 493 | sessionBuffer.getExistingSession({ |
| 494 | projectId, |
| 495 | deviceId: currentDeviceId, |
| 496 | }), |
| 497 | sessionBuffer.getExistingSession({ |
| 498 | projectId, |
| 499 | deviceId: previousDeviceId, |
| 500 | }), |
| 501 | ]); |
| 502 | |
| 503 | // Blob has no TTL — only treat the session as "current" if its last |
| 504 | // event is within the idle window. Otherwise the SDK should ask the |
| 505 | // server to start a fresh session id on the next event. |
| 506 | const now = Date.now(); |
| 507 | const isLive = (s: typeof current) => |
| 508 | !!s && |
| 509 | now - convertClickhouseDateToJs(s.ended_at).getTime() < |
| 510 | SESSION_TIMEOUT_MS; |
| 511 | |
| 512 | if (current && isLive(current)) { |
| 513 | return reply.status(200).send({ |
| 514 | deviceId: currentDeviceId, |
| 515 | sessionId: current.id, |
nothing calls this directly
no test coverage detected