mirror of
https://github.com/wu736139669/hapi.git
synced 2026-11-30 06:17:06 +00:00
refactor: decompose Store into domain-specific substore classes
This commit is contained in:
+1
-1
@@ -89,7 +89,7 @@ async function main() {
|
||||
const socketServer = createSocketServer({
|
||||
store,
|
||||
jwtSecret,
|
||||
getSession: (sessionId) => syncEngine?.getSession(sessionId) ?? store.getSession(sessionId),
|
||||
getSession: (sessionId) => syncEngine?.getSession(sessionId) ?? store.sessions.getSession(sessionId),
|
||||
onWebappEvent: (event: SyncEvent) => syncEngine?.handleRealtimeEvent(event),
|
||||
onSessionAlive: (payload) => syncEngine?.handleSessionAlive(payload),
|
||||
onSessionEnd: (payload) => syncEngine?.handleSessionEnd(payload),
|
||||
|
||||
@@ -37,7 +37,7 @@ export class PushService {
|
||||
}
|
||||
|
||||
async sendToNamespace(namespace: string, payload: PushPayload): Promise<void> {
|
||||
const subscriptions = this.store.getPushSubscriptionsByNamespace(namespace)
|
||||
const subscriptions = this.store.push.getPushSubscriptionsByNamespace(namespace)
|
||||
if (subscriptions.length === 0) {
|
||||
return
|
||||
}
|
||||
@@ -69,7 +69,7 @@ export class PushService {
|
||||
: null
|
||||
|
||||
if (statusCode === 410) {
|
||||
this.store.removePushSubscription(namespace, subscription.endpoint)
|
||||
this.store.push.removePushSubscription(namespace, subscription.endpoint)
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
@@ -54,11 +54,11 @@ export function registerCliHandlers(socket: SocketWithData, deps: CliHandlersDep
|
||||
if (!namespace) {
|
||||
return { ok: false, reason: 'namespace-missing' }
|
||||
}
|
||||
const session = store.getSessionByNamespace(sessionId, namespace)
|
||||
const session = store.sessions.getSessionByNamespace(sessionId, namespace)
|
||||
if (session) {
|
||||
return { ok: true, value: session }
|
||||
}
|
||||
if (store.getSession(sessionId)) {
|
||||
if (store.sessions.getSession(sessionId)) {
|
||||
return { ok: false, reason: 'access-denied' }
|
||||
}
|
||||
return { ok: false, reason: 'not-found' }
|
||||
@@ -68,11 +68,11 @@ export function registerCliHandlers(socket: SocketWithData, deps: CliHandlersDep
|
||||
if (!namespace) {
|
||||
return { ok: false, reason: 'namespace-missing' }
|
||||
}
|
||||
const machine = store.getMachineByNamespace(machineId, namespace)
|
||||
const machine = store.machines.getMachineByNamespace(machineId, namespace)
|
||||
if (machine) {
|
||||
return { ok: true, value: machine }
|
||||
}
|
||||
if (store.getMachine(machineId)) {
|
||||
if (store.machines.getMachine(machineId)) {
|
||||
return { ok: false, reason: 'access-denied' }
|
||||
}
|
||||
return { ok: false, reason: 'not-found' }
|
||||
|
||||
@@ -68,7 +68,7 @@ export function registerMachineHandlers(socket: SocketWithData, deps: MachineHan
|
||||
return
|
||||
}
|
||||
|
||||
const result = store.updateMachineMetadata(id, metadata, expectedVersion, machineAccess.value.namespace)
|
||||
const result = store.machines.updateMachineMetadata(id, metadata, expectedVersion, machineAccess.value.namespace)
|
||||
if (result.result === 'success') {
|
||||
cb({ result: 'success', version: result.version, metadata: result.value })
|
||||
} else if (result.result === 'version-mismatch') {
|
||||
@@ -108,7 +108,12 @@ export function registerMachineHandlers(socket: SocketWithData, deps: MachineHan
|
||||
return
|
||||
}
|
||||
|
||||
const result = store.updateMachineDaemonState(id, daemonState, expectedVersion, machineAccess.value.namespace)
|
||||
const result = store.machines.updateMachineDaemonState(
|
||||
id,
|
||||
daemonState,
|
||||
expectedVersion,
|
||||
machineAccess.value.namespace
|
||||
)
|
||||
if (result.result === 'success') {
|
||||
cb({ result: 'success', version: result.version, daemonState: result.value })
|
||||
} else if (result.result === 'version-mismatch') {
|
||||
|
||||
@@ -86,11 +86,11 @@ export function registerSessionHandlers(socket: SocketWithData, deps: SessionHan
|
||||
}
|
||||
const session = sessionAccess.value
|
||||
|
||||
const msg = store.addMessage(sid, content, localId)
|
||||
const msg = store.messages.addMessage(sid, content, localId)
|
||||
|
||||
const todos = extractTodoWriteTodosFromMessageContent(content)
|
||||
if (todos) {
|
||||
const updated = store.setSessionTodos(sid, todos, msg.createdAt, session.namespace)
|
||||
const updated = store.sessions.setSessionTodos(sid, todos, msg.createdAt, session.namespace)
|
||||
if (updated) {
|
||||
onWebappEvent?.({ type: 'session-updated', sessionId: sid, data: { sid } })
|
||||
}
|
||||
@@ -141,7 +141,12 @@ export function registerSessionHandlers(socket: SocketWithData, deps: SessionHan
|
||||
return
|
||||
}
|
||||
|
||||
const result = store.updateSessionMetadata(sid, metadata, expectedVersion, sessionAccess.value.namespace)
|
||||
const result = store.sessions.updateSessionMetadata(
|
||||
sid,
|
||||
metadata,
|
||||
expectedVersion,
|
||||
sessionAccess.value.namespace
|
||||
)
|
||||
if (result.result === 'success') {
|
||||
cb({ result: 'success', version: result.version, metadata: result.value })
|
||||
} else if (result.result === 'version-mismatch') {
|
||||
@@ -181,7 +186,12 @@ export function registerSessionHandlers(socket: SocketWithData, deps: SessionHan
|
||||
return
|
||||
}
|
||||
|
||||
const result = store.updateSessionAgentState(sid, agentState, expectedVersion, sessionAccess.value.namespace)
|
||||
const result = store.sessions.updateSessionAgentState(
|
||||
sid,
|
||||
agentState,
|
||||
expectedVersion,
|
||||
sessionAccess.value.namespace
|
||||
)
|
||||
if (result.result === 'success') {
|
||||
cb({ result: 'success', version: result.version, agentState: result.value })
|
||||
} else if (result.result === 'version-mismatch') {
|
||||
|
||||
@@ -138,7 +138,7 @@ export function createSocketServer(deps: SocketServerDeps): {
|
||||
})
|
||||
terminalNs.on('connection', (socket) => registerTerminalHandlers(socket, {
|
||||
io,
|
||||
getSession: (sessionId) => deps.getSession?.(sessionId) ?? deps.store.getSession(sessionId),
|
||||
getSession: (sessionId) => deps.getSession?.(sessionId) ?? deps.store.sessions.getSession(sessionId),
|
||||
terminalRegistry,
|
||||
maxTerminalsPerSocket,
|
||||
maxTerminalsPerSession
|
||||
|
||||
+22
-178
@@ -2,47 +2,11 @@ import { Database } from 'bun:sqlite'
|
||||
import { chmodSync, closeSync, existsSync, mkdirSync, openSync } from 'node:fs'
|
||||
import { dirname } from 'node:path'
|
||||
|
||||
import type {
|
||||
StoredMachine,
|
||||
StoredMessage,
|
||||
StoredPushSubscription,
|
||||
StoredSession,
|
||||
StoredUser,
|
||||
VersionedUpdateResult
|
||||
} from './types'
|
||||
import {
|
||||
deleteSession,
|
||||
getOrCreateSession,
|
||||
getSession,
|
||||
getSessionByNamespace,
|
||||
getSessions,
|
||||
getSessionsByNamespace,
|
||||
setSessionTodos,
|
||||
updateSessionAgentState,
|
||||
updateSessionMetadata
|
||||
} from './sessions'
|
||||
import {
|
||||
getMachine,
|
||||
getMachineByNamespace,
|
||||
getMachines,
|
||||
getMachinesByNamespace,
|
||||
getOrCreateMachine,
|
||||
updateMachineDaemonState,
|
||||
updateMachineMetadata
|
||||
} from './machines'
|
||||
import { addMessage, getMessages, getMessagesAfter } from './messages'
|
||||
import {
|
||||
addUser,
|
||||
getUser,
|
||||
getUsersByPlatform,
|
||||
getUsersByPlatformAndNamespace,
|
||||
removeUser
|
||||
} from './users'
|
||||
import {
|
||||
addPushSubscription,
|
||||
getPushSubscriptionsByNamespace,
|
||||
removePushSubscription
|
||||
} from './pushSubscriptions'
|
||||
import { MachineStore } from './machineStore'
|
||||
import { MessageStore } from './messageStore'
|
||||
import { PushStore } from './pushStore'
|
||||
import { SessionStore } from './sessionStore'
|
||||
import { UserStore } from './userStore'
|
||||
|
||||
export type {
|
||||
StoredMachine,
|
||||
@@ -52,6 +16,11 @@ export type {
|
||||
StoredUser,
|
||||
VersionedUpdateResult
|
||||
} from './types'
|
||||
export { MachineStore } from './machineStore'
|
||||
export { MessageStore } from './messageStore'
|
||||
export { PushStore } from './pushStore'
|
||||
export { SessionStore } from './sessionStore'
|
||||
export { UserStore } from './userStore'
|
||||
|
||||
const SCHEMA_VERSION = 1
|
||||
const REQUIRED_TABLES = [
|
||||
@@ -66,6 +35,12 @@ export class Store {
|
||||
private db: Database
|
||||
private readonly dbPath: string
|
||||
|
||||
readonly sessions: SessionStore
|
||||
readonly machines: MachineStore
|
||||
readonly messages: MessageStore
|
||||
readonly users: UserStore
|
||||
readonly push: PushStore
|
||||
|
||||
constructor(dbPath: string) {
|
||||
this.dbPath = dbPath
|
||||
if (dbPath !== ':memory:' && !dbPath.startsWith('file::memory:')) {
|
||||
@@ -100,6 +75,12 @@ export class Store {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
this.sessions = new SessionStore(this.db)
|
||||
this.machines = new MachineStore(this.db)
|
||||
this.messages = new MessageStore(this.db)
|
||||
this.users = new UserStore(this.db)
|
||||
this.push = new PushStore(this.db)
|
||||
}
|
||||
|
||||
private initSchema(): void {
|
||||
@@ -238,141 +219,4 @@ export class Store {
|
||||
'Back up and rebuild the database, or run an offline migration to the expected schema version.'
|
||||
)
|
||||
}
|
||||
|
||||
getOrCreateSession(tag: string, metadata: unknown, agentState: unknown, namespace: string): StoredSession {
|
||||
return getOrCreateSession(this.db, tag, metadata, agentState, namespace)
|
||||
}
|
||||
|
||||
updateSessionMetadata(
|
||||
id: string,
|
||||
metadata: unknown,
|
||||
expectedVersion: number,
|
||||
namespace: string,
|
||||
options?: { touchUpdatedAt?: boolean }
|
||||
): VersionedUpdateResult<unknown | null> {
|
||||
return updateSessionMetadata(this.db, id, metadata, expectedVersion, namespace, options)
|
||||
}
|
||||
|
||||
updateSessionAgentState(
|
||||
id: string,
|
||||
agentState: unknown,
|
||||
expectedVersion: number,
|
||||
namespace: string
|
||||
): VersionedUpdateResult<unknown | null> {
|
||||
return updateSessionAgentState(this.db, id, agentState, expectedVersion, namespace)
|
||||
}
|
||||
|
||||
setSessionTodos(id: string, todos: unknown, todosUpdatedAt: number, namespace: string): boolean {
|
||||
return setSessionTodos(this.db, id, todos, todosUpdatedAt, namespace)
|
||||
}
|
||||
|
||||
getSession(id: string): StoredSession | null {
|
||||
return getSession(this.db, id)
|
||||
}
|
||||
|
||||
getSessionByNamespace(id: string, namespace: string): StoredSession | null {
|
||||
return getSessionByNamespace(this.db, id, namespace)
|
||||
}
|
||||
|
||||
getSessions(): StoredSession[] {
|
||||
return getSessions(this.db)
|
||||
}
|
||||
|
||||
getSessionsByNamespace(namespace: string): StoredSession[] {
|
||||
return getSessionsByNamespace(this.db, namespace)
|
||||
}
|
||||
|
||||
getOrCreateMachine(id: string, metadata: unknown, daemonState: unknown, namespace: string): StoredMachine {
|
||||
return getOrCreateMachine(this.db, id, metadata, daemonState, namespace)
|
||||
}
|
||||
|
||||
updateMachineMetadata(
|
||||
id: string,
|
||||
metadata: unknown,
|
||||
expectedVersion: number,
|
||||
namespace: string
|
||||
): VersionedUpdateResult<unknown | null> {
|
||||
return updateMachineMetadata(this.db, id, metadata, expectedVersion, namespace)
|
||||
}
|
||||
|
||||
updateMachineDaemonState(
|
||||
id: string,
|
||||
daemonState: unknown,
|
||||
expectedVersion: number,
|
||||
namespace: string
|
||||
): VersionedUpdateResult<unknown | null> {
|
||||
return updateMachineDaemonState(this.db, id, daemonState, expectedVersion, namespace)
|
||||
}
|
||||
|
||||
getMachine(id: string): StoredMachine | null {
|
||||
return getMachine(this.db, id)
|
||||
}
|
||||
|
||||
getMachineByNamespace(id: string, namespace: string): StoredMachine | null {
|
||||
return getMachineByNamespace(this.db, id, namespace)
|
||||
}
|
||||
|
||||
getMachines(): StoredMachine[] {
|
||||
return getMachines(this.db)
|
||||
}
|
||||
|
||||
getMachinesByNamespace(namespace: string): StoredMachine[] {
|
||||
return getMachinesByNamespace(this.db, namespace)
|
||||
}
|
||||
|
||||
addMessage(sessionId: string, content: unknown, localId?: string): StoredMessage {
|
||||
return addMessage(this.db, sessionId, content, localId)
|
||||
}
|
||||
|
||||
getMessages(sessionId: string, limit: number = 200, beforeSeq?: number): StoredMessage[] {
|
||||
return getMessages(this.db, sessionId, limit, beforeSeq)
|
||||
}
|
||||
|
||||
getMessagesAfter(sessionId: string, afterSeq: number, limit: number = 200): StoredMessage[] {
|
||||
return getMessagesAfter(this.db, sessionId, afterSeq, limit)
|
||||
}
|
||||
|
||||
getUser(platform: string, platformUserId: string): StoredUser | null {
|
||||
return getUser(this.db, platform, platformUserId)
|
||||
}
|
||||
|
||||
getUsersByPlatform(platform: string): StoredUser[] {
|
||||
return getUsersByPlatform(this.db, platform)
|
||||
}
|
||||
|
||||
getUsersByPlatformAndNamespace(platform: string, namespace: string): StoredUser[] {
|
||||
return getUsersByPlatformAndNamespace(this.db, platform, namespace)
|
||||
}
|
||||
|
||||
addUser(platform: string, platformUserId: string, namespace: string): StoredUser {
|
||||
return addUser(this.db, platform, platformUserId, namespace)
|
||||
}
|
||||
|
||||
removeUser(platform: string, platformUserId: string): boolean {
|
||||
return removeUser(this.db, platform, platformUserId)
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a session and all associated data.
|
||||
* Messages are automatically cascade-deleted via foreign key constraint.
|
||||
* Todos are stored in the sessions.todos column and deleted with the row.
|
||||
*/
|
||||
deleteSession(id: string, namespace: string): boolean {
|
||||
return deleteSession(this.db, id, namespace)
|
||||
}
|
||||
|
||||
addPushSubscription(
|
||||
namespace: string,
|
||||
subscription: { endpoint: string; p256dh: string; auth: string }
|
||||
): void {
|
||||
addPushSubscription(this.db, namespace, subscription)
|
||||
}
|
||||
|
||||
removePushSubscription(namespace: string, endpoint: string): void {
|
||||
removePushSubscription(this.db, namespace, endpoint)
|
||||
}
|
||||
|
||||
getPushSubscriptionsByNamespace(namespace: string): StoredPushSubscription[] {
|
||||
return getPushSubscriptionsByNamespace(this.db, namespace)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
import type { Database } from 'bun:sqlite'
|
||||
|
||||
import type { StoredMachine, VersionedUpdateResult } from './types'
|
||||
import {
|
||||
getMachine,
|
||||
getMachineByNamespace,
|
||||
getMachines,
|
||||
getMachinesByNamespace,
|
||||
getOrCreateMachine,
|
||||
updateMachineDaemonState,
|
||||
updateMachineMetadata
|
||||
} from './machines'
|
||||
|
||||
export class MachineStore {
|
||||
private readonly db: Database
|
||||
|
||||
constructor(db: Database) {
|
||||
this.db = db
|
||||
}
|
||||
|
||||
getOrCreateMachine(id: string, metadata: unknown, daemonState: unknown, namespace: string): StoredMachine {
|
||||
return getOrCreateMachine(this.db, id, metadata, daemonState, namespace)
|
||||
}
|
||||
|
||||
updateMachineMetadata(
|
||||
id: string,
|
||||
metadata: unknown,
|
||||
expectedVersion: number,
|
||||
namespace: string
|
||||
): VersionedUpdateResult<unknown | null> {
|
||||
return updateMachineMetadata(this.db, id, metadata, expectedVersion, namespace)
|
||||
}
|
||||
|
||||
updateMachineDaemonState(
|
||||
id: string,
|
||||
daemonState: unknown,
|
||||
expectedVersion: number,
|
||||
namespace: string
|
||||
): VersionedUpdateResult<unknown | null> {
|
||||
return updateMachineDaemonState(this.db, id, daemonState, expectedVersion, namespace)
|
||||
}
|
||||
|
||||
getMachine(id: string): StoredMachine | null {
|
||||
return getMachine(this.db, id)
|
||||
}
|
||||
|
||||
getMachineByNamespace(id: string, namespace: string): StoredMachine | null {
|
||||
return getMachineByNamespace(this.db, id, namespace)
|
||||
}
|
||||
|
||||
getMachines(): StoredMachine[] {
|
||||
return getMachines(this.db)
|
||||
}
|
||||
|
||||
getMachinesByNamespace(namespace: string): StoredMachine[] {
|
||||
return getMachinesByNamespace(this.db, namespace)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import type { Database } from 'bun:sqlite'
|
||||
|
||||
import type { StoredMessage } from './types'
|
||||
import { addMessage, getMessages, getMessagesAfter } from './messages'
|
||||
|
||||
export class MessageStore {
|
||||
private readonly db: Database
|
||||
|
||||
constructor(db: Database) {
|
||||
this.db = db
|
||||
}
|
||||
|
||||
addMessage(sessionId: string, content: unknown, localId?: string): StoredMessage {
|
||||
return addMessage(this.db, sessionId, content, localId)
|
||||
}
|
||||
|
||||
getMessages(sessionId: string, limit: number = 200, beforeSeq?: number): StoredMessage[] {
|
||||
return getMessages(this.db, sessionId, limit, beforeSeq)
|
||||
}
|
||||
|
||||
getMessagesAfter(sessionId: string, afterSeq: number, limit: number = 200): StoredMessage[] {
|
||||
return getMessagesAfter(this.db, sessionId, afterSeq, limit)
|
||||
}
|
||||
}
|
||||
@@ -4,10 +4,10 @@ import { Store } from './index'
|
||||
describe('Store namespace filtering', () => {
|
||||
it('filters sessions by namespace', () => {
|
||||
const store = new Store(':memory:')
|
||||
const sessionAlpha = store.getOrCreateSession('tag', { path: '/alpha' }, null, 'alpha')
|
||||
const sessionBeta = store.getOrCreateSession('tag', { path: '/beta' }, null, 'beta')
|
||||
const sessionAlpha = store.sessions.getOrCreateSession('tag', { path: '/alpha' }, null, 'alpha')
|
||||
const sessionBeta = store.sessions.getOrCreateSession('tag', { path: '/beta' }, null, 'beta')
|
||||
|
||||
const sessionsAlpha = store.getSessionsByNamespace('alpha')
|
||||
const sessionsAlpha = store.sessions.getSessionsByNamespace('alpha')
|
||||
const ids = sessionsAlpha.map((session) => session.id)
|
||||
|
||||
expect(ids).toContain(sessionAlpha.id)
|
||||
@@ -16,14 +16,14 @@ describe('Store namespace filtering', () => {
|
||||
|
||||
it('filters machines by namespace and blocks mismatches', () => {
|
||||
const store = new Store(':memory:')
|
||||
const machineAlpha = store.getOrCreateMachine('machine-1', { host: 'alpha' }, null, 'alpha')
|
||||
store.getOrCreateMachine('machine-2', { host: 'beta' }, null, 'beta')
|
||||
const machineAlpha = store.machines.getOrCreateMachine('machine-1', { host: 'alpha' }, null, 'alpha')
|
||||
store.machines.getOrCreateMachine('machine-2', { host: 'beta' }, null, 'beta')
|
||||
|
||||
const machinesAlpha = store.getMachinesByNamespace('alpha')
|
||||
const machinesAlpha = store.machines.getMachinesByNamespace('alpha')
|
||||
const ids = machinesAlpha.map((machine) => machine.id)
|
||||
|
||||
expect(ids).toContain(machineAlpha.id)
|
||||
expect(ids).not.toContain('machine-2')
|
||||
expect(() => store.getOrCreateMachine('machine-1', { host: 'beta' }, null, 'beta')).toThrow()
|
||||
expect(() => store.machines.getOrCreateMachine('machine-1', { host: 'beta' }, null, 'beta')).toThrow()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
import type { Database } from 'bun:sqlite'
|
||||
|
||||
import type { StoredPushSubscription } from './types'
|
||||
import { addPushSubscription, getPushSubscriptionsByNamespace, removePushSubscription } from './pushSubscriptions'
|
||||
|
||||
export class PushStore {
|
||||
private readonly db: Database
|
||||
|
||||
constructor(db: Database) {
|
||||
this.db = db
|
||||
}
|
||||
|
||||
addPushSubscription(namespace: string, subscription: { endpoint: string; p256dh: string; auth: string }): void {
|
||||
addPushSubscription(this.db, namespace, subscription)
|
||||
}
|
||||
|
||||
removePushSubscription(namespace: string, endpoint: string): void {
|
||||
removePushSubscription(this.db, namespace, endpoint)
|
||||
}
|
||||
|
||||
getPushSubscriptionsByNamespace(namespace: string): StoredPushSubscription[] {
|
||||
return getPushSubscriptionsByNamespace(this.db, namespace)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import type { Database } from 'bun:sqlite'
|
||||
|
||||
import type { StoredSession, VersionedUpdateResult } from './types'
|
||||
import {
|
||||
deleteSession,
|
||||
getOrCreateSession,
|
||||
getSession,
|
||||
getSessionByNamespace,
|
||||
getSessions,
|
||||
getSessionsByNamespace,
|
||||
setSessionTodos,
|
||||
updateSessionAgentState,
|
||||
updateSessionMetadata
|
||||
} from './sessions'
|
||||
|
||||
export class SessionStore {
|
||||
private readonly db: Database
|
||||
|
||||
constructor(db: Database) {
|
||||
this.db = db
|
||||
}
|
||||
|
||||
getOrCreateSession(tag: string, metadata: unknown, agentState: unknown, namespace: string): StoredSession {
|
||||
return getOrCreateSession(this.db, tag, metadata, agentState, namespace)
|
||||
}
|
||||
|
||||
updateSessionMetadata(
|
||||
id: string,
|
||||
metadata: unknown,
|
||||
expectedVersion: number,
|
||||
namespace: string,
|
||||
options?: { touchUpdatedAt?: boolean }
|
||||
): VersionedUpdateResult<unknown | null> {
|
||||
return updateSessionMetadata(this.db, id, metadata, expectedVersion, namespace, options)
|
||||
}
|
||||
|
||||
updateSessionAgentState(
|
||||
id: string,
|
||||
agentState: unknown,
|
||||
expectedVersion: number,
|
||||
namespace: string
|
||||
): VersionedUpdateResult<unknown | null> {
|
||||
return updateSessionAgentState(this.db, id, agentState, expectedVersion, namespace)
|
||||
}
|
||||
|
||||
setSessionTodos(id: string, todos: unknown, todosUpdatedAt: number, namespace: string): boolean {
|
||||
return setSessionTodos(this.db, id, todos, todosUpdatedAt, namespace)
|
||||
}
|
||||
|
||||
getSession(id: string): StoredSession | null {
|
||||
return getSession(this.db, id)
|
||||
}
|
||||
|
||||
getSessionByNamespace(id: string, namespace: string): StoredSession | null {
|
||||
return getSessionByNamespace(this.db, id, namespace)
|
||||
}
|
||||
|
||||
getSessions(): StoredSession[] {
|
||||
return getSessions(this.db)
|
||||
}
|
||||
|
||||
getSessionsByNamespace(namespace: string): StoredSession[] {
|
||||
return getSessionsByNamespace(this.db, namespace)
|
||||
}
|
||||
|
||||
deleteSession(id: string, namespace: string): boolean {
|
||||
return deleteSession(this.db, id, namespace)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import type { Database } from 'bun:sqlite'
|
||||
|
||||
import type { StoredUser } from './types'
|
||||
import { addUser, getUser, getUsersByPlatform, getUsersByPlatformAndNamespace, removeUser } from './users'
|
||||
|
||||
export class UserStore {
|
||||
private readonly db: Database
|
||||
|
||||
constructor(db: Database) {
|
||||
this.db = db
|
||||
}
|
||||
|
||||
getUser(platform: string, platformUserId: string): StoredUser | null {
|
||||
return getUser(this.db, platform, platformUserId)
|
||||
}
|
||||
|
||||
getUsersByPlatform(platform: string): StoredUser[] {
|
||||
return getUsersByPlatform(this.db, platform)
|
||||
}
|
||||
|
||||
getUsersByPlatformAndNamespace(platform: string, namespace: string): StoredUser[] {
|
||||
return getUsersByPlatformAndNamespace(this.db, platform, namespace)
|
||||
}
|
||||
|
||||
addUser(platform: string, platformUserId: string, namespace: string): StoredUser {
|
||||
return addUser(this.db, platform, platformUserId, namespace)
|
||||
}
|
||||
|
||||
removeUser(platform: string, platformUserId: string): boolean {
|
||||
return removeUser(this.db, platform, platformUserId)
|
||||
}
|
||||
}
|
||||
@@ -69,12 +69,12 @@ export class MachineCache {
|
||||
}
|
||||
|
||||
getOrCreateMachine(id: string, metadata: unknown, daemonState: unknown, namespace: string): Machine {
|
||||
const stored = this.store.getOrCreateMachine(id, metadata, daemonState, namespace)
|
||||
const stored = this.store.machines.getOrCreateMachine(id, metadata, daemonState, namespace)
|
||||
return this.refreshMachine(stored.id) ?? (() => { throw new Error('Failed to load machine') })()
|
||||
}
|
||||
|
||||
refreshMachine(machineId: string): Machine | null {
|
||||
const stored = this.store.getMachine(machineId)
|
||||
const stored = this.store.machines.getMachine(machineId)
|
||||
if (!stored) {
|
||||
const existed = this.machines.delete(machineId)
|
||||
if (existed) {
|
||||
@@ -120,7 +120,7 @@ export class MachineCache {
|
||||
}
|
||||
|
||||
reloadAll(): void {
|
||||
const machines = this.store.getMachines()
|
||||
const machines = this.store.machines.getMachines()
|
||||
for (const machine of machines) {
|
||||
this.refreshMachine(machine.id)
|
||||
}
|
||||
|
||||
@@ -20,7 +20,7 @@ export class MessageService {
|
||||
hasMore: boolean
|
||||
}
|
||||
} {
|
||||
const stored = this.store.getMessages(sessionId, options.limit, options.beforeSeq ?? undefined)
|
||||
const stored = this.store.messages.getMessages(sessionId, options.limit, options.beforeSeq ?? undefined)
|
||||
const messages: DecryptedMessage[] = stored.map((message) => ({
|
||||
id: message.id,
|
||||
seq: message.seq,
|
||||
@@ -38,7 +38,8 @@ export class MessageService {
|
||||
}
|
||||
|
||||
const nextBeforeSeq = oldestSeq
|
||||
const hasMore = nextBeforeSeq !== null && this.store.getMessages(sessionId, 1, nextBeforeSeq).length > 0
|
||||
const hasMore = nextBeforeSeq !== null
|
||||
&& this.store.messages.getMessages(sessionId, 1, nextBeforeSeq).length > 0
|
||||
|
||||
return {
|
||||
messages,
|
||||
@@ -52,7 +53,7 @@ export class MessageService {
|
||||
}
|
||||
|
||||
getMessagesAfter(sessionId: string, options: { afterSeq: number; limit: number }): DecryptedMessage[] {
|
||||
const stored = this.store.getMessagesAfter(sessionId, options.afterSeq, options.limit)
|
||||
const stored = this.store.messages.getMessagesAfter(sessionId, options.afterSeq, options.limit)
|
||||
return stored.map((message) => ({
|
||||
id: message.id,
|
||||
seq: message.seq,
|
||||
@@ -79,7 +80,7 @@ export class MessageService {
|
||||
}
|
||||
}
|
||||
|
||||
const msg = this.store.addMessage(sessionId, content, payload.localId ?? undefined)
|
||||
const msg = this.store.messages.addMessage(sessionId, content, payload.localId ?? undefined)
|
||||
|
||||
const update = {
|
||||
id: msg.id,
|
||||
|
||||
@@ -41,12 +41,12 @@ export class SessionCache {
|
||||
}
|
||||
|
||||
getOrCreateSession(tag: string, metadata: unknown, agentState: unknown, namespace: string): Session {
|
||||
const stored = this.store.getOrCreateSession(tag, metadata, agentState, namespace)
|
||||
const stored = this.store.sessions.getOrCreateSession(tag, metadata, agentState, namespace)
|
||||
return this.refreshSession(stored.id) ?? (() => { throw new Error('Failed to load session') })()
|
||||
}
|
||||
|
||||
refreshSession(sessionId: string): Session | null {
|
||||
let stored = this.store.getSession(sessionId)
|
||||
let stored = this.store.sessions.getSession(sessionId)
|
||||
if (!stored) {
|
||||
const existed = this.sessions.delete(sessionId)
|
||||
if (existed) {
|
||||
@@ -59,14 +59,14 @@ export class SessionCache {
|
||||
|
||||
if (stored.todos === null && !this.todoBackfillAttemptedSessionIds.has(sessionId)) {
|
||||
this.todoBackfillAttemptedSessionIds.add(sessionId)
|
||||
const messages = this.store.getMessages(sessionId, 200)
|
||||
const messages = this.store.messages.getMessages(sessionId, 200)
|
||||
for (let i = messages.length - 1; i >= 0; i -= 1) {
|
||||
const message = messages[i]
|
||||
const todos = extractTodoWriteTodosFromMessageContent(message.content)
|
||||
if (todos) {
|
||||
const updated = this.store.setSessionTodos(sessionId, todos, message.createdAt, stored.namespace)
|
||||
const updated = this.store.sessions.setSessionTodos(sessionId, todos, message.createdAt, stored.namespace)
|
||||
if (updated) {
|
||||
stored = this.store.getSession(sessionId) ?? stored
|
||||
stored = this.store.sessions.getSession(sessionId) ?? stored
|
||||
}
|
||||
break
|
||||
}
|
||||
@@ -114,7 +114,7 @@ export class SessionCache {
|
||||
}
|
||||
|
||||
reloadAll(): void {
|
||||
const sessions = this.store.getSessions()
|
||||
const sessions = this.store.sessions.getSessions()
|
||||
for (const session of sessions) {
|
||||
this.refreshSession(session.id)
|
||||
}
|
||||
@@ -227,7 +227,7 @@ export class SessionCache {
|
||||
const currentMetadata = session.metadata ?? { path: '', host: '' }
|
||||
const newMetadata = { ...currentMetadata, name }
|
||||
|
||||
const result = this.store.updateSessionMetadata(
|
||||
const result = this.store.sessions.updateSessionMetadata(
|
||||
sessionId,
|
||||
newMetadata,
|
||||
session.metadataVersion,
|
||||
@@ -256,7 +256,7 @@ export class SessionCache {
|
||||
throw new Error('Cannot delete active session')
|
||||
}
|
||||
|
||||
const deleted = this.store.deleteSession(sessionId, session.namespace)
|
||||
const deleted = this.store.sessions.deleteSession(sessionId, session.namespace)
|
||||
if (!deleted) {
|
||||
throw new Error('Failed to delete session')
|
||||
}
|
||||
|
||||
@@ -162,7 +162,7 @@ export class HappyBot implements NotificationChannel {
|
||||
* Get bound Telegram chat IDs from storage.
|
||||
*/
|
||||
private getBoundChatIds(namespace: string): number[] {
|
||||
const users = this.store.getUsersByPlatformAndNamespace('telegram', namespace)
|
||||
const users = this.store.users.getUsersByPlatformAndNamespace('telegram', namespace)
|
||||
const ids = new Set<number>()
|
||||
for (const user of users) {
|
||||
const chatId = Number(user.platformUserId)
|
||||
@@ -177,7 +177,7 @@ export class HappyBot implements NotificationChannel {
|
||||
if (!chatId) {
|
||||
return null
|
||||
}
|
||||
const stored = this.store.getUser('telegram', String(chatId))
|
||||
const stored = this.store.users.getUser('telegram', String(chatId))
|
||||
return stored?.namespace ?? null
|
||||
}
|
||||
|
||||
|
||||
@@ -56,7 +56,7 @@ export function createAuthRoutes(jwtSecret: Uint8Array, store: Store): Hono<WebA
|
||||
}
|
||||
|
||||
const telegramUserId = String(result.user.id)
|
||||
const storedUser = store.getUser('telegram', telegramUserId)
|
||||
const storedUser = store.users.getUser('telegram', telegramUserId)
|
||||
if (!storedUser) {
|
||||
return c.json({ error: 'not_bound' }, 401)
|
||||
}
|
||||
|
||||
@@ -40,11 +40,11 @@ export function createBindRoutes(jwtSecret: Uint8Array, store: Store): Hono<WebA
|
||||
}
|
||||
|
||||
const telegramUserId = String(result.user.id)
|
||||
const existingUser = store.getUser('telegram', telegramUserId)
|
||||
const existingUser = store.users.getUser('telegram', telegramUserId)
|
||||
if (existingUser && existingUser.namespace !== namespace) {
|
||||
return c.json({ error: 'already_bound' }, 409)
|
||||
}
|
||||
store.addUser('telegram', telegramUserId, namespace)
|
||||
store.users.addUser('telegram', telegramUserId, namespace)
|
||||
|
||||
const userId = await getOrCreateOwnerId()
|
||||
|
||||
|
||||
@@ -31,7 +31,7 @@ export function createPushRoutes(store: Store, vapidPublicKey: string): Hono<Web
|
||||
|
||||
const namespace = c.get('namespace')
|
||||
const { endpoint, keys } = parsed.data
|
||||
store.addPushSubscription(namespace, {
|
||||
store.push.addPushSubscription(namespace, {
|
||||
endpoint,
|
||||
p256dh: keys.p256dh,
|
||||
auth: keys.auth
|
||||
@@ -48,7 +48,7 @@ export function createPushRoutes(store: Store, vapidPublicKey: string): Hono<Web
|
||||
}
|
||||
|
||||
const namespace = c.get('namespace')
|
||||
store.removePushSubscription(namespace, parsed.data.endpoint)
|
||||
store.push.removePushSubscription(namespace, parsed.data.endpoint)
|
||||
return c.json({ ok: true })
|
||||
})
|
||||
|
||||
|
||||
Reference in New Issue
Block a user