Spaces:
Sleeping
Sleeping
File size: 5,347 Bytes
f4656a0 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 | 'use strict';
const { getDb, getDbType } = require('../config/database');
const { v4: uuidv4 } = require('uuid');
const SESSION_TIMEOUT_MINUTES = parseInt(process.env.SESSION_TIMEOUT_MINUTES || '30');
/**
* Session model β manages conversation sessions across channels.
* Each session is isolated per user+channel combination.
*/
const SessionModel = {
/**
* Create a new session for a user on a given channel.
*/
async create({ userId, channel, metadata = {} }) {
const db = getDb();
const id = uuidv4();
const expiresAt = new Date(Date.now() + SESSION_TIMEOUT_MINUTES * 60 * 1000);
if (getDbType() === 'sqlite') {
db.prepare(`
INSERT INTO sessions (id, channel, user_id, responses, metadata, expires_at)
VALUES (?, ?, ?, ?, ?, ?)
`).run(id, channel, userId, '[]', JSON.stringify(metadata), expiresAt.toISOString());
} else {
await db.query(
`INSERT INTO sessions (id, channel, user_id, responses, metadata, expires_at)
VALUES ($1, $2, $3, $4, $5, $6)`,
[id, channel, userId, '[]', JSON.stringify(metadata), expiresAt]
);
}
return this.findById(id);
},
/**
* Find session by ID.
*/
async findById(id) {
const db = getDb();
if (getDbType() === 'sqlite') {
const row = db.prepare('SELECT * FROM sessions WHERE id = ?').get(id);
return row ? parseSession(row) : null;
} else {
const { rows } = await db.query('SELECT * FROM sessions WHERE id = $1', [id]);
return rows[0] ? parseSession(rows[0]) : null;
}
},
/**
* Find the most recent active (non-expired) session for a user+channel.
*/
async findActiveByUserChannel(userId, channel) {
const db = getDb();
const now = new Date().toISOString();
if (getDbType() === 'sqlite') {
const row = db.prepare(`
SELECT * FROM sessions
WHERE user_id = ? AND channel = ? AND expires_at > ?
ORDER BY created_at DESC LIMIT 1
`).get(userId, channel, now);
return row ? parseSession(row) : null;
} else {
const { rows } = await db.query(
`SELECT * FROM sessions
WHERE user_id = $1 AND channel = $2 AND expires_at > NOW()
ORDER BY created_at DESC LIMIT 1`,
[userId, channel]
);
return rows[0] ? parseSession(rows[0]) : null;
}
},
/**
* Update session state after each question answer.
*/
async update(id, updates) {
const db = getDb();
const expiresAt = new Date(Date.now() + SESSION_TIMEOUT_MINUTES * 60 * 1000);
const fields = { ...updates, expires_at: expiresAt };
if (getDbType() === 'sqlite') {
const setClauses = [];
const values = [];
for (const [key, val] of Object.entries(fields)) {
const col = camelToSnake(key);
setClauses.push(`${col} = ?`);
values.push(toSQLiteValue(val));
}
values.push(id);
db.prepare(`UPDATE sessions SET ${setClauses.join(', ')}, updated_at = datetime('now') WHERE id = ?`).run(...values);
} else {
const setClauses = [];
const values = [];
let i = 1;
for (const [key, val] of Object.entries(fields)) {
const col = camelToSnake(key);
setClauses.push(`${col} = $${i++}`);
values.push(typeof val === 'object' && val !== null ? JSON.stringify(val) : val);
}
values.push(id);
await db.query(
`UPDATE sessions SET ${setClauses.join(', ')}, updated_at = NOW() WHERE id = $${i}`,
values
);
}
return this.findById(id);
},
/**
* Delete a session (used for reset).
*/
async delete(id) {
const db = getDb();
if (getDbType() === 'sqlite') {
db.prepare('DELETE FROM sessions WHERE id = ?').run(id);
} else {
await db.query('DELETE FROM sessions WHERE id = $1', [id]);
}
},
/**
* Remove all expired sessions (called by cleanup cron job).
*/
async deleteExpired() {
const db = getDb();
const now = new Date().toISOString();
if (getDbType() === 'sqlite') {
const result = db.prepare('DELETE FROM sessions WHERE expires_at < ?').run(now);
return result.changes;
} else {
const { rowCount } = await db.query('DELETE FROM sessions WHERE expires_at < NOW()');
return rowCount;
}
},
};
/**
* Convert a JS value to a SQLite-compatible type.
* Booleans β integer, Date β ISO string, objects β JSON string.
*/
function toSQLiteValue(val) {
if (val === null || val === undefined) return null;
if (typeof val === 'boolean') return val ? 1 : 0;
if (val instanceof Date) return val.toISOString();
if (typeof val === 'object') return JSON.stringify(val);
return val;
}
function parseSession(row) {
return {
...row,
responses: typeof row.responses === 'string' ? JSON.parse(row.responses) : row.responses || [],
recommendations: row.recommendations
? typeof row.recommendations === 'string'
? JSON.parse(row.recommendations)
: row.recommendations
: null,
metadata: typeof row.metadata === 'string' ? JSON.parse(row.metadata) : row.metadata || {},
completed: row.completed === 1 || row.completed === true,
};
}
function camelToSnake(str) {
return str.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`);
}
module.exports = SessionModel;
|