-
Notifications
You must be signed in to change notification settings - Fork 2
/
Sessions.fs
265 lines (240 loc) · 10.4 KB
/
Sessions.fs
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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
namespace FsOpenAI.GenAI
open System
open System.Text.Json
open FSharp.Control
open System.Threading.Channels
open FsOpenAI.Shared
open FSharp.CosmosDb
module Version =
let version = "0.1.0" //serialize format version change this when conversion to new format is required
type SessionMsg = {
Role : string
Content : string
}
type ChatSession = {
[<Id>]
id: string
[<PartitionKey>]
UserId : string
AppId : string
Timestamp : DateTime
Version : string
Interaction : Interaction
}
type SessionOp =
| Upsert of ChatSession
| Delete of InvocationContext*string
| ClearAll of InvocationContext
[<RequireQualifiedAccess>]
module Sessions =
let BUFFER_SIZE = 1000
let BUFFER_WAIT = 10000
let MAX_SESSIONS = 15
let mutable private _cnctnInfo = lazy None
let init (ccstr,database,container) =
match Connection.tryCreate<ChatSession>(ccstr,database,container) with
| Some x -> _cnctnInfo <- lazy(Some x)
| None -> ()
let getConnectionFromConfig() =
try
Env.appConfig.Value
|> Option.bind(fun x -> Env.logInfo $"{x.DatabaseName},{x.SessionTableName}"; x.SessionTableName |> Option.map(fun t -> x.DatabaseName,t))
|> Option.bind(fun (database,container) ->
Settings.getSettings().Value.LOG_CONN_STR
|> Option.map(fun cstr -> Env.logInfo $"{Utils.shorten 30 cstr}";cstr,database,container))
with ex ->
Env.logException (ex,"Monitoring.getConnectionFromConfig")
None
let ensureConnection() =
match _cnctnInfo.Value with
| Some _ -> ()
| None ->
match getConnectionFromConfig() with
| Some (cstr,db,cntnr) -> init(cstr,db,cntnr)
| None -> ()
type SREf = {[<Id>] id:string; [<PartitionKey>] UserId:string; Timestamp:DateTime}
let private saveSessionsForUser ((userId:string,appId:string), chatSessions:ChatSession[]) =
async {
match _cnctnInfo.Value with
| Some c ->
try
let db =
Cosmos.fromConnectionString c.ConnectionString
|> Cosmos.database c.DatabaseName
|> Cosmos.container c.ContainerName
do!
db
|> Cosmos.upsertMany (Array.toList chatSessions)
|> Cosmos.execAsync
|> AsyncSeq.iter (fun _ -> ())
let ls =
db
|> Cosmos.query<SREf>(sprintf $"SELECT c.id, c.UserId, c.Timestamp FROM c WHERE c.UserId = @UserId and c.AppId = @AppId" )
|> Cosmos.parameters ["@UserId", box userId; "@AppId", box appId]
|> Cosmos.execAsync
|> AsyncSeq.toBlockingSeq
|> Seq.toList
let sessions = ls |> List.sortBy(fun x -> x.Timestamp)
if sessions.Length > MAX_SESSIONS then
let dropSessions = sessions |> List.take (MAX_SESSIONS - sessions.Length)
do!
dropSessions
|> AsyncSeq.ofSeq
|> AsyncSeq.iterAsync (fun c ->
db
|> Cosmos.deleteItem<ChatSession> c.id c.UserId
|> Cosmos.execAsync
|> AsyncSeq.iterAsync Async.Ignore)
with ex ->
Env.logException (ex,"Sessions.saveSessionsForUser: ")
| None -> ()
}
let private saveSessions (chatSessions:ChatSession[]) =
async {
match _cnctnInfo.Value with
| Some _ ->
try
do!
chatSessions
|> Array.groupBy(fun x -> x.UserId,x.AppId)
|> Array.map saveSessionsForUser
|> Async.Parallel
|> Async.Ignore
with ex ->
Env.logException (ex,"Sessions.saveSessions: ")
| None -> ()
}
let private channel = Channel.CreateBounded<SessionOp>(BoundedChannelOptions(BUFFER_SIZE,FullMode = BoundedChannelFullMode.DropOldest))
let private delete (invCtx:InvocationContext,id:string) =
async {
match _cnctnInfo.Value with
| Some c ->
try
let user = invCtx.User |> Option.defaultValue null
let db =
Cosmos.fromConnectionString c.ConnectionString
|> Cosmos.database c.DatabaseName
|> Cosmos.container c.ContainerName
do!
db
|> Cosmos.deleteItem<ChatSession> id user
|> Cosmos.execAsync
|> AsyncSeq.iter (fun _ -> ())
with ex ->
Env.logException (ex,"Sessions.delete: ")
| None -> ()
}
let private clearAll (invCtx:InvocationContext) =
async {
match _cnctnInfo.Value with
| Some c ->
try
let db =
Cosmos.fromConnectionString c.ConnectionString
|> Cosmos.database c.DatabaseName
|> Cosmos.container c.ContainerName
let userId = invCtx.User |> Option.defaultValue C.UNAUTHENTICATED
let appId = invCtx.AppId |> Option.defaultValue C.DFLT_APP_ID
let dropSessions =
db
|> Cosmos.query<SREf>(sprintf $"SELECT c.id, c.UserId, c.Timestamp FROM c WHERE c.UserId = @UserId and c.AppId = @AppId" )
|> Cosmos.parameters ["@UserId", box userId; "@AppId", box appId]
|> Cosmos.execAsync
|> AsyncSeq.toBlockingSeq
|> Seq.toList
do!
dropSessions
|> AsyncSeq.ofSeq
|> AsyncSeq.iterAsync (fun c ->
async {
try
do!
db
|> Cosmos.deleteItem<ChatSession> c.id c.UserId
|> Cosmos.execAsync
|> AsyncSeq.iter (fun x -> ())
with ex ->
Env.logError ex.Message
})
with ex ->
Env.logException (ex,"Sessions.delete: ")
| None -> ()
}
let private applyOps (ops:SessionOp[]) =
async {
let gops = ops |> Array.groupBy (function | Upsert _ -> 0 | Delete _ -> 1 | ClearAll _ -> 2)
for (k,ops) in gops do
match k with
| 0 ->
do!
ops
|> Array.choose (fun op -> match op with | Upsert session -> Some session | _ -> None)
|> saveSessions
| 1 ->
do!
ops
|> AsyncSeq.ofSeq
|> AsyncSeq.choose (fun op -> match op with | Delete (invCtx,id) -> Some (invCtx,id) | _ -> None)
|> AsyncSeq.iterAsync delete
| 2 ->
do!
ops
|> AsyncSeq.ofSeq
|> AsyncSeq.choose (fun ops -> match ops with | ClearAll invCtx -> Some invCtx | _ -> None)
|> AsyncSeq.iterAsync clearAll
| x -> failwith $"operaion type {x} not handled in applyOps"
}
//background loop to read channel and write diagnostics entry to backend
let private consumerLoop =
asyncSeq {
while true do
let! data = channel.Reader.ReadAsync().AsTask() |> Async.AwaitTask
yield data
}
|> AsyncSeq.bufferByCountAndTime 10 BUFFER_WAIT
|> AsyncSeq.iterAsync applyOps
|> Async.Start
let queueOp session = channel.Writer.WriteAsync session |> ignore
let toSession (invCtx:InvocationContext) (ch:Interaction) =
let userId = invCtx.User |> Option.defaultValue C.UNAUTHENTICATED
let appId = invCtx.AppId |> Option.defaultValue C.DFLT_APP_ID
let timestamp = DateTime.UtcNow
{
id = ch.Id
UserId = userId
AppId = appId
Timestamp = timestamp
Version = Version.version
Interaction = ch
}
let tryConvert (str:string,ch:JsonDocument) =
let ver = ch.RootElement.GetProperty("Version").GetString()
if ver = Version.version then
let sess = System.Text.Json.JsonSerializer.Deserialize<ChatSession>(str,Utils.serOptions())
//let sess = Newtonsoft.Json.JsonConvert.DeserializeObject<ChatSession>(str)
Some sess.Interaction
else
//TODO: convert to new verison from old serialized format
None
let loadSessions (invCtx:InvocationContext) =
let userId = invCtx.User |> Option.defaultValue C.UNAUTHENTICATED
let appId = invCtx.AppId |> Option.defaultValue C.DFLT_APP_ID
match _cnctnInfo.Value with
| Some c ->
let db =
Cosmos.fromConnectionString c.ConnectionString
|> Cosmos.database c.DatabaseName
|> Cosmos.container c.ContainerName
db
|> Cosmos.query<SREf>(sprintf $"SELECT c.id, c.UserId, c.Timestamp FROM c WHERE c.UserId = @UserId and c.AppId = @AppId ORDER BY c.Timestamp DESC" )
|> Cosmos.parameters ["@UserId", box userId; "@AppId", box appId]
|> Cosmos.execAsync
|> AsyncSeq.collect (fun sref ->
db
|> Cosmos.read sref.id sref.UserId
|> Cosmos.execAsync)
|> AsyncSeq.map(fun j ->
let doc = j.ToString()
doc,System.Text.Json.JsonDocument.Parse(doc))
|> AsyncSeq.choose tryConvert
| None -> AsyncSeq.empty