Compare commits

..

2 Commits

Author SHA1 Message Date
7b1341b1ca test: remove weak active session test
Co-authored-by: Ona <no-reply@ona.com>
2026-03-21 18:55:44 +00:00
f6ea1b7204 feat(backend): add admin API with provider config endpoint
Add /api/admin/* route group with admin role middleware and a
PUT /api/admin/:sourceId/config endpoint for updating feed source
provider config at runtime. Currently supports aelis.weather.

Co-authored-by: Ona <no-reply@ona.com>
2026-03-21 18:46:28 +00:00
13 changed files with 143 additions and 396 deletions

View File

@@ -1,7 +1,7 @@
import type { ActionDefinition, ContextEntry, FeedItem, FeedSource } from "@aelis/core"
import { describe, expect, mock, test } from "bun:test"
import { Hono } from "hono"
import { describe, expect, test } from "bun:test"
import type { AdminMiddleware } from "../auth/admin-middleware.ts"
import type { AuthSession, AuthUser } from "../auth/session.ts"
@@ -11,39 +11,6 @@ import type { FeedSourceProvider } from "../session/feed-source-provider.ts"
import { UserSessionManager } from "../session/user-session-manager.ts"
import { registerAdminHttpHandlers } from "./http.ts"
let mockEnabledSourceIds: string[] = []
mock.module("../sources/user-sources.ts", () => ({
sources: (_db: Database, _userId: string) => ({
async enabled() {
const now = new Date()
return mockEnabledSourceIds.map((sourceId) => ({
id: crypto.randomUUID(),
userId: _userId,
sourceId,
enabled: true,
config: {},
credentials: null,
createdAt: now,
updatedAt: now,
}))
},
async find(sourceId: string) {
const now = new Date()
return {
id: crypto.randomUUID(),
userId: _userId,
sourceId,
enabled: true,
config: {},
credentials: null,
createdAt: now,
updatedAt: now,
}
},
}),
}))
function createStubSource(id: string): FeedSource {
return {
id,
@@ -96,8 +63,7 @@ function passthroughAdminMiddleware(): AdminMiddleware {
const fakeDb = {} as Database
function createApp(providers: FeedSourceProvider[]) {
mockEnabledSourceIds = providers.map((p) => p.sourceId)
const sessionManager = new UserSessionManager({ db: fakeDb, providers })
const sessionManager = new UserSessionManager({ providers })
const app = new Hono()
registerAdminHttpHandlers(app, {
sessionManager,
@@ -192,4 +158,5 @@ describe("PUT /api/admin/:sourceId/config", () => {
expect(provider!.sourceId).toBe("aelis.weather")
expect(provider).not.toBe(originalProvider)
})
})

View File

@@ -51,6 +51,7 @@ async function handleUpdateProviderConfig(c: Context<Env>) {
}
const sessionManager = c.get("sessionManager")
const db = c.get("db")
let body: unknown
try {
@@ -67,6 +68,7 @@ async function handleUpdateProviderConfig(c: Context<Env>) {
}
const updated = new WeatherSourceProvider({
db,
credentials: parsed.credentials,
})

View File

@@ -1,11 +1,9 @@
import type { ActionDefinition, ContextEntry, FeedItem, FeedSource } from "@aelis/core"
import { contextKey } from "@aelis/core"
import { describe, expect, mock, spyOn, test } from "bun:test"
import { describe, expect, spyOn, test } from "bun:test"
import { Hono } from "hono"
import type { Database } from "../db/index.ts"
import { mockAuthSessionMiddleware } from "../auth/session-middleware.ts"
import { UserSessionManager } from "../session/index.ts"
import { registerFeedHttpHandlers } from "./http.ts"
@@ -52,45 +50,9 @@ function buildTestApp(sessionManager: UserSessionManager, userId?: string) {
return app
}
let mockEnabledSourceIds: string[] = []
mock.module("../sources/user-sources.ts", () => ({
sources: (_db: Database, _userId: string) => ({
async enabled() {
const now = new Date()
return mockEnabledSourceIds.map((sourceId) => ({
id: crypto.randomUUID(),
userId: _userId,
sourceId,
enabled: true,
config: {},
credentials: null,
createdAt: now,
updatedAt: now,
}))
},
async find(sourceId: string) {
const now = new Date()
return {
id: crypto.randomUUID(),
userId: _userId,
sourceId,
enabled: true,
config: {},
credentials: null,
createdAt: now,
updatedAt: now,
}
},
}),
}))
const fakeDb = {} as Database
describe("GET /api/feed", () => {
test("returns 401 without auth", async () => {
mockEnabledSourceIds = []
const manager = new UserSessionManager({ db: fakeDb, providers: [] })
const manager = new UserSessionManager({ providers: [] })
const app = buildTestApp(manager)
const res = await app.request("/api/feed")
@@ -109,9 +71,7 @@ describe("GET /api/feed", () => {
data: { value: 42 },
},
]
mockEnabledSourceIds = ["test"]
const manager = new UserSessionManager({
db: fakeDb,
providers: [
{
sourceId: "test",
@@ -151,9 +111,7 @@ describe("GET /api/feed", () => {
data: { fresh: true },
},
]
mockEnabledSourceIds = ["test"]
const manager = new UserSessionManager({
db: fakeDb,
providers: [
{
sourceId: "test",
@@ -192,9 +150,7 @@ describe("GET /api/feed", () => {
throw new Error("connection timeout")
},
}
mockEnabledSourceIds = ["failing"]
const manager = new UserSessionManager({
db: fakeDb,
providers: [
{
sourceId: "failing",
@@ -217,9 +173,7 @@ describe("GET /api/feed", () => {
})
test("returns 503 when all providers fail", async () => {
mockEnabledSourceIds = ["test"]
const manager = new UserSessionManager({
db: fakeDb,
providers: [
{
sourceId: "test",
@@ -252,9 +206,7 @@ describe("GET /api/context", () => {
const mockUserId = "k7Gx2mPqRvNwYs9TdLfA4bHcJeUo1iZn"
async function buildContextApp(userId?: string) {
mockEnabledSourceIds = ["weather"]
const manager = new UserSessionManager({
db: fakeDb,
providers: [
{
sourceId: "weather",
@@ -270,8 +222,7 @@ describe("GET /api/context", () => {
}
test("returns 401 without auth", async () => {
mockEnabledSourceIds = []
const manager = new UserSessionManager({ db: fakeDb, providers: [] })
const manager = new UserSessionManager({ providers: [] })
const app = buildTestApp(manager)
const res = await app.request('/api/context?key=["aelis.weather","weather"]')

View File

@@ -1,11 +1,26 @@
import { LocationSource } from "@aelis/source-location"
import type { Database } from "../db/index.ts"
import type { FeedSourceProvider } from "../session/feed-source-provider.ts"
import { SourceDisabledError } from "../sources/errors.ts"
import { sources } from "../sources/user-sources.ts"
export class LocationSourceProvider implements FeedSourceProvider {
readonly sourceId = "aelis.location"
private readonly db: Database
constructor(db: Database) {
this.db = db
}
async feedSourceForUser(userId: string): Promise<LocationSource> {
const row = await sources(this.db, userId).find("aelis.location")
if (!row || !row.enabled) {
throw new SourceDisabledError("aelis.location", userId)
}
async feedSourceForUser(_userId: string, _config: unknown): Promise<LocationSource> {
return new LocationSource()
}
}

View File

@@ -32,10 +32,10 @@ function main() {
}
const sessionManager = new UserSessionManager({
db,
providers: [
new LocationSourceProvider(),
new LocationSourceProvider(db),
new WeatherSourceProvider({
db,
credentials: {
privateKey: process.env.WEATHERKIT_PRIVATE_KEY!,
keyId: process.env.WEATHERKIT_KEY_ID!,

View File

@@ -3,5 +3,5 @@ import type { FeedSource } from "@aelis/core"
export interface FeedSourceProvider {
/** The source ID this provider is responsible for (e.g., "aelis.location"). */
readonly sourceId: string
feedSourceForUser(userId: string, config: unknown): Promise<FeedSource>
feedSourceForUser(userId: string): Promise<FeedSource>
}

View File

@@ -2,77 +2,12 @@ import type { ActionDefinition, ContextEntry, FeedItem, FeedSource } from "@aeli
import { LocationSource } from "@aelis/source-location"
import { WeatherSource } from "@aelis/source-weatherkit"
import { beforeEach, describe, expect, mock, spyOn, test } from "bun:test"
import { describe, expect, mock, spyOn, test } from "bun:test"
import type { Database } from "../db/index.ts"
import type { FeedSourceProvider } from "./feed-source-provider.ts"
import { UserSessionManager } from "./user-session-manager.ts"
/**
* Per-user enabled source IDs used by the mocked `sources` module.
* Tests configure this before calling getOrCreate.
* Key = userId (or "*" for a default), value = array of enabled sourceIds.
*/
const enabledByUser = new Map<string, string[]>()
/** Set which sourceIds are enabled for all users. */
function setEnabledSources(sourceIds: string[]) {
enabledByUser.clear()
enabledByUser.set("*", sourceIds)
}
/** Set which sourceIds are enabled for a specific user. */
function setEnabledSourcesForUser(userId: string, sourceIds: string[]) {
enabledByUser.set(userId, sourceIds)
}
function getEnabledSourceIds(userId: string): string[] {
return enabledByUser.get(userId) ?? enabledByUser.get("*") ?? []
}
/**
* Controls what `find()` returns in the mock. When `undefined` (the default),
* `find()` returns a standard enabled row. Set to a specific value (including
* `null`) to override the return value for all `find()` calls.
*/
let mockFindResult: unknown | undefined
// Mock the sources module so UserSessionManager's DB query returns controlled data.
mock.module("../sources/user-sources.ts", () => ({
sources: (_db: Database, userId: string) => ({
async enabled() {
const now = new Date()
return getEnabledSourceIds(userId).map((sourceId) => ({
id: crypto.randomUUID(),
userId,
sourceId,
enabled: true,
config: {},
credentials: null,
createdAt: now,
updatedAt: now,
}))
},
async find(sourceId: string) {
if (mockFindResult !== undefined) return mockFindResult
const now = new Date()
return {
id: crypto.randomUUID(),
userId,
sourceId,
enabled: true,
config: {},
credentials: null,
createdAt: now,
updatedAt: now,
}
},
}),
}))
const fakeDb = {} as Database
function createStubSource(id: string, items: FeedItem[] = []): FeedSource {
return {
id,
@@ -93,8 +28,7 @@ function createStubSource(id: string, items: FeedItem[] = []): FeedSource {
function createStubProvider(
sourceId: string,
factory: (userId: string, config: Record<string, unknown>) => Promise<FeedSource> = async () =>
createStubSource(sourceId),
factory: (userId: string) => Promise<FeedSource> = async () => createStubSource(sourceId),
): FeedSourceProvider {
return { sourceId, feedSourceForUser: factory }
}
@@ -113,15 +47,9 @@ const weatherProvider: FeedSourceProvider = {
},
}
beforeEach(() => {
enabledByUser.clear()
mockFindResult = undefined
})
describe("UserSessionManager", () => {
test("getOrCreate creates session on first call", async () => {
setEnabledSources(["aelis.location"])
const manager = new UserSessionManager({ db: fakeDb, providers: [locationProvider] })
const manager = new UserSessionManager({ providers: [locationProvider] })
const session = await manager.getOrCreate("user-1")
@@ -130,8 +58,7 @@ describe("UserSessionManager", () => {
})
test("getOrCreate returns same session for same user", async () => {
setEnabledSources(["aelis.location"])
const manager = new UserSessionManager({ db: fakeDb, providers: [locationProvider] })
const manager = new UserSessionManager({ providers: [locationProvider] })
const session1 = await manager.getOrCreate("user-1")
const session2 = await manager.getOrCreate("user-1")
@@ -140,8 +67,7 @@ describe("UserSessionManager", () => {
})
test("getOrCreate returns different sessions for different users", async () => {
setEnabledSources(["aelis.location"])
const manager = new UserSessionManager({ db: fakeDb, providers: [locationProvider] })
const manager = new UserSessionManager({ providers: [locationProvider] })
const session1 = await manager.getOrCreate("user-1")
const session2 = await manager.getOrCreate("user-2")
@@ -150,8 +76,7 @@ describe("UserSessionManager", () => {
})
test("each user gets independent source instances", async () => {
setEnabledSources(["aelis.location"])
const manager = new UserSessionManager({ db: fakeDb, providers: [locationProvider] })
const manager = new UserSessionManager({ providers: [locationProvider] })
const session1 = await manager.getOrCreate("user-1")
const session2 = await manager.getOrCreate("user-2")
@@ -163,8 +88,7 @@ describe("UserSessionManager", () => {
})
test("remove destroys session and allows re-creation", async () => {
setEnabledSources(["aelis.location"])
const manager = new UserSessionManager({ db: fakeDb, providers: [locationProvider] })
const manager = new UserSessionManager({ providers: [locationProvider] })
const session1 = await manager.getOrCreate("user-1")
manager.remove("user-1")
@@ -174,16 +98,13 @@ describe("UserSessionManager", () => {
})
test("remove is no-op for unknown user", () => {
setEnabledSources(["aelis.location"])
const manager = new UserSessionManager({ db: fakeDb, providers: [locationProvider] })
const manager = new UserSessionManager({ providers: [locationProvider] })
expect(() => manager.remove("unknown")).not.toThrow()
})
test("registers multiple providers", async () => {
setEnabledSources(["aelis.location", "aelis.weather"])
const manager = new UserSessionManager({
db: fakeDb,
providers: [locationProvider, weatherProvider],
})
@@ -194,8 +115,7 @@ describe("UserSessionManager", () => {
})
test("refresh returns feed result through session", async () => {
setEnabledSources(["aelis.location"])
const manager = new UserSessionManager({ db: fakeDb, providers: [locationProvider] })
const manager = new UserSessionManager({ providers: [locationProvider] })
const session = await manager.getOrCreate("user-1")
const result = await session.engine.refresh()
@@ -207,8 +127,7 @@ describe("UserSessionManager", () => {
})
test("location update via executeAction works", async () => {
setEnabledSources(["aelis.location"])
const manager = new UserSessionManager({ db: fakeDb, providers: [locationProvider] })
const manager = new UserSessionManager({ providers: [locationProvider] })
const session = await manager.getOrCreate("user-1")
await session.engine.executeAction("aelis.location", "update-location", {
@@ -223,8 +142,7 @@ describe("UserSessionManager", () => {
})
test("subscribe receives updates after location push", async () => {
setEnabledSources(["aelis.location"])
const manager = new UserSessionManager({ db: fakeDb, providers: [locationProvider] })
const manager = new UserSessionManager({ providers: [locationProvider] })
const callback = mock()
const session = await manager.getOrCreate("user-1")
@@ -244,8 +162,7 @@ describe("UserSessionManager", () => {
})
test("remove stops reactive updates", async () => {
setEnabledSources(["aelis.location"])
const manager = new UserSessionManager({ db: fakeDb, providers: [locationProvider] })
const manager = new UserSessionManager({ providers: [locationProvider] })
const callback = mock()
const session = await manager.getOrCreate("user-1")
@@ -268,7 +185,6 @@ describe("UserSessionManager", () => {
})
test("creates session with successful providers when some fail", async () => {
setEnabledSources(["aelis.location", "aelis.failing"])
const failingProvider: FeedSourceProvider = {
sourceId: "aelis.failing",
async feedSourceForUser() {
@@ -277,7 +193,6 @@ describe("UserSessionManager", () => {
}
const manager = new UserSessionManager({
db: fakeDb,
providers: [locationProvider, failingProvider],
})
@@ -293,9 +208,7 @@ describe("UserSessionManager", () => {
})
test("throws AggregateError when all providers fail", async () => {
setEnabledSources(["aelis.fail-1", "aelis.fail-2"])
const manager = new UserSessionManager({
db: fakeDb,
providers: [
{
sourceId: "aelis.fail-1",
@@ -316,10 +229,8 @@ describe("UserSessionManager", () => {
})
test("concurrent getOrCreate for same user returns same session", async () => {
setEnabledSources(["aelis.location"])
let callCount = 0
const manager = new UserSessionManager({
db: fakeDb,
providers: [
{
sourceId: "aelis.location",
@@ -342,14 +253,12 @@ describe("UserSessionManager", () => {
})
test("remove during in-flight getOrCreate prevents session from being stored", async () => {
setEnabledSources(["aelis.location"])
let resolveProvider: () => void
const providerGate = new Promise<void>((r) => {
resolveProvider = r
})
const manager = new UserSessionManager({
db: fakeDb,
providers: [
{
sourceId: "aelis.location",
@@ -376,67 +285,10 @@ describe("UserSessionManager", () => {
expect(freshSession).toBeDefined()
expect(freshSession.engine).toBeDefined()
})
test("only invokes providers for sources enabled for the user", async () => {
setEnabledSources(["aelis.location"])
const locationFactory = mock(async () => createStubSource("aelis.location"))
const weatherFactory = mock(async () => createStubSource("aelis.weather"))
const manager = new UserSessionManager({
db: fakeDb,
providers: [
{ sourceId: "aelis.location", feedSourceForUser: locationFactory },
{ sourceId: "aelis.weather", feedSourceForUser: weatherFactory },
],
})
const session = await manager.getOrCreate("user-1")
expect(locationFactory).toHaveBeenCalledTimes(1)
expect(weatherFactory).not.toHaveBeenCalled()
expect(session.getSource("aelis.location")).toBeDefined()
expect(session.getSource("aelis.weather")).toBeUndefined()
})
test("creates empty session when no sources are enabled", async () => {
setEnabledSources([])
const factory = mock(async () => createStubSource("aelis.location"))
const manager = new UserSessionManager({
db: fakeDb,
providers: [{ sourceId: "aelis.location", feedSourceForUser: factory }],
})
const session = await manager.getOrCreate("user-1")
expect(factory).not.toHaveBeenCalled()
expect(session).toBeDefined()
expect(session.getSource("aelis.location")).toBeUndefined()
})
test("per-user enabled sources are respected", async () => {
enabledByUser.clear()
setEnabledSourcesForUser("user-1", ["aelis.location"])
setEnabledSourcesForUser("user-2", ["aelis.weather"])
const manager = new UserSessionManager({
db: fakeDb,
providers: [createStubProvider("aelis.location"), createStubProvider("aelis.weather")],
})
const session1 = await manager.getOrCreate("user-1")
const session2 = await manager.getOrCreate("user-2")
expect(session1.getSource("aelis.location")).toBeDefined()
expect(session1.getSource("aelis.weather")).toBeUndefined()
expect(session2.getSource("aelis.location")).toBeUndefined()
expect(session2.getSource("aelis.weather")).toBeDefined()
})
})
describe("UserSessionManager.replaceProvider", () => {
test("replaces source in all active sessions", async () => {
setEnabledSources(["test"])
const itemsV1: FeedItem[] = [
{
id: "v1",
@@ -457,7 +309,7 @@ describe("UserSessionManager.replaceProvider", () => {
]
const providerV1 = createStubProvider("test", async () => createStubSource("test", itemsV1))
const manager = new UserSessionManager({ db: fakeDb, providers: [providerV1] })
const manager = new UserSessionManager({ providers: [providerV1] })
const session1 = await manager.getOrCreate("user-1")
const session2 = await manager.getOrCreate("user-2")
@@ -478,8 +330,7 @@ describe("UserSessionManager.replaceProvider", () => {
})
test("throws for unknown provider sourceId", async () => {
setEnabledSources(["aelis.location"])
const manager = new UserSessionManager({ db: fakeDb, providers: [locationProvider] })
const manager = new UserSessionManager({ providers: [locationProvider] })
const unknownProvider = createStubProvider("aelis.unknown")
@@ -488,10 +339,9 @@ describe("UserSessionManager.replaceProvider", () => {
)
})
test("keeps existing source when new provider fails for a user", async () => {
setEnabledSources(["test"])
test("removes source from session when new provider fails for a user", async () => {
const providerV1 = createStubProvider("test", async () => createStubSource("test"))
const manager = new UserSessionManager({ db: fakeDb, providers: [providerV1] })
const manager = new UserSessionManager({ providers: [providerV1] })
const session = await manager.getOrCreate("user-1")
expect(session.getSource("test")).toBeDefined()
@@ -503,14 +353,13 @@ describe("UserSessionManager.replaceProvider", () => {
})
await manager.replaceProvider(failingProvider)
expect(session.getSource("test")).toBeDefined()
expect(session.getSource("test")).toBeUndefined()
expect(spy).toHaveBeenCalled()
spy.mockRestore()
})
test("new sessions use the replaced provider", async () => {
setEnabledSources(["test"])
const itemsV1: FeedItem[] = [
{
id: "v1",
@@ -531,7 +380,7 @@ describe("UserSessionManager.replaceProvider", () => {
]
const providerV1 = createStubProvider("test", async () => createStubSource("test", itemsV1))
const manager = new UserSessionManager({ db: fakeDb, providers: [providerV1] })
const manager = new UserSessionManager({ providers: [providerV1] })
const providerV2 = createStubProvider("test", async () => createStubSource("test", itemsV2))
await manager.replaceProvider(providerV2)
@@ -543,7 +392,6 @@ describe("UserSessionManager.replaceProvider", () => {
})
test("does not affect other providers' sources", async () => {
setEnabledSources(["source-a", "source-b"])
const providerA = createStubProvider("source-a", async () =>
createStubSource("source-a", [
{
@@ -567,7 +415,7 @@ describe("UserSessionManager.replaceProvider", () => {
]),
)
const manager = new UserSessionManager({ db: fakeDb, providers: [providerA, providerB] })
const manager = new UserSessionManager({ providers: [providerA, providerB] })
const session = await manager.getOrCreate("user-1")
// Replace only source-a
@@ -592,7 +440,6 @@ describe("UserSessionManager.replaceProvider", () => {
})
test("updates sessions that are still being created", async () => {
setEnabledSources(["test"])
const itemsV1: FeedItem[] = [
{
id: "v1",
@@ -621,7 +468,7 @@ describe("UserSessionManager.replaceProvider", () => {
await creationGate
return createStubSource("test", itemsV1)
})
const manager = new UserSessionManager({ db: fakeDb, providers: [providerV1] })
const manager = new UserSessionManager({ providers: [providerV1] })
// Start session creation but don't let it finish yet
const sessionPromise = manager.getOrCreate("user-1")
@@ -640,44 +487,4 @@ describe("UserSessionManager.replaceProvider", () => {
const feed = await session.feed()
expect(feed.items[0]!.data.version).toBe(2)
})
test("skips source replacement when source was disabled between creation and replace", async () => {
setEnabledSources(["test"])
const itemsV1: FeedItem[] = [
{
id: "v1",
sourceId: "test",
type: "test",
timestamp: new Date(),
data: { version: 1 },
},
]
const providerV1 = createStubProvider("test", async () => createStubSource("test", itemsV1))
const manager = new UserSessionManager({ db: fakeDb, providers: [providerV1] })
const session = await manager.getOrCreate("user-1")
const feedBefore = await session.feed()
expect(feedBefore.items[0]!.data.version).toBe(1)
// Simulate the source being disabled/deleted between session creation and replace
mockFindResult = null
const providerV2 = createStubProvider("test", async () =>
createStubSource("test", [
{
id: "v2",
sourceId: "test",
type: "test",
timestamp: new Date(),
data: { version: 2 },
},
]),
)
await manager.replaceProvider(providerV2)
// Session should still have v1 — the replace was skipped
const feedAfter = await session.feed()
expect(feedAfter.items[0]!.data.version).toBe(1)
})
})

View File

@@ -1,27 +1,22 @@
import type { FeedSource } from "@aelis/core"
import type { Database } from "../db/index.ts"
import type { FeedEnhancer } from "../enhancement/enhance-feed.ts"
import type { FeedSourceProvider } from "./feed-source-provider.ts"
import { sources } from "../sources/user-sources.ts"
import { UserSession } from "./user-session.ts"
export interface UserSessionManagerConfig {
db: Database
providers: FeedSourceProvider[]
feedEnhancer?: FeedEnhancer | null
}
export class UserSessionManager {
private sessions = new Map<string, UserSession>()
private sessions = new Map<string, { userId: string; session: UserSession }>()
private pending = new Map<string, Promise<UserSession>>()
private readonly db: Database
private readonly providers = new Map<string, FeedSourceProvider>()
private readonly feedEnhancer: FeedEnhancer | null
constructor(config: UserSessionManagerConfig) {
this.db = config.db
for (const provider of config.providers) {
this.providers.set(provider.sourceId, provider)
}
@@ -34,7 +29,7 @@ export class UserSessionManager {
async getOrCreate(userId: string): Promise<UserSession> {
const existing = this.sessions.get(userId)
if (existing) return existing
if (existing) return existing.session
const inflight = this.pending.get(userId)
if (inflight) return inflight
@@ -49,7 +44,7 @@ export class UserSessionManager {
session.destroy()
throw new Error(`Session for user ${userId} was removed during creation`)
}
this.sessions.set(userId, session)
this.sessions.set(userId, { userId, session })
return session
} finally {
this.pending.delete(userId)
@@ -57,9 +52,9 @@ export class UserSessionManager {
}
remove(userId: string): void {
const session = this.sessions.get(userId)
if (session) {
session.destroy()
const entry = this.sessions.get(userId)
if (entry) {
entry.session.destroy()
this.sessions.delete(userId)
}
// Cancel any in-flight creation so getOrCreate won't store the session
@@ -69,9 +64,8 @@ export class UserSessionManager {
/**
* Replaces a provider and updates all active sessions.
* The new provider must have the same sourceId as an existing one.
* For each active session, queries the user's source config from the DB
* and re-resolves the source. If the provider fails for a user, the
* existing source is kept.
* For each active session, resolves a new source from the provider.
* If the provider fails for a user, the old source is removed from that session.
*/
async replaceProvider(provider: FeedSourceProvider): Promise<void> {
if (!this.providers.has(provider.sourceId)) {
@@ -84,16 +78,16 @@ export class UserSessionManager {
const updates: Promise<void>[] = []
for (const [, session] of this.sessions) {
updates.push(this.refreshSessionSource(session, provider))
for (const [, { userId, session }] of this.sessions) {
updates.push(this.updateSessionSource(provider, userId, session))
}
// Also update sessions that are currently being created so they
// don't land in this.sessions with a stale source.
for (const [, pendingPromise] of this.pending) {
for (const [userId, pendingPromise] of this.pending) {
updates.push(
pendingPromise
.then((session) => this.refreshSessionSource(session, provider))
.then((session) => this.updateSessionSource(provider, userId, session))
.catch(() => {
// Session creation itself failed — nothing to update.
}),
@@ -103,60 +97,40 @@ export class UserSessionManager {
await Promise.all(updates)
}
/**
* Re-resolves a single source for a session by querying the user's config
* from the DB and calling the provider. If the provider fails, the existing
* source is kept.
*/
private async refreshSessionSource(
session: UserSession,
private async updateSessionSource(
provider: FeedSourceProvider,
userId: string,
session: UserSession,
): Promise<void> {
if (!session.hasSource(provider.sourceId)) return
try {
const row = await sources(this.db, session.userId).find(provider.sourceId)
if (!row?.enabled) return
const newSource = await provider.feedSourceForUser(session.userId, row.config ?? {})
const newSource = await provider.feedSourceForUser(userId)
session.replaceSource(provider.sourceId, newSource)
} catch (err) {
console.error(
`[UserSessionManager] refreshSource("${provider.sourceId}") failed for user ${session.userId}:`,
`[UserSessionManager] replaceProvider("${provider.sourceId}") failed for user ${userId}:`,
err,
)
session.removeSource(provider.sourceId)
}
}
private async createSession(userId: string): Promise<UserSession> {
const enabledRows = await sources(this.db, userId).enabled()
const results = await Promise.allSettled(
Array.from(this.providers.values()).map((p) => p.feedSourceForUser(userId)),
)
const promises: Promise<FeedSource>[] = []
for (const row of enabledRows) {
const provider = this.providers.get(row.sourceId)
if (provider) {
promises.push(provider.feedSourceForUser(userId, row.config ?? {}))
}
}
if (promises.length === 0) {
return new UserSession(userId, [], this.feedEnhancer)
}
const results = await Promise.allSettled(promises)
const feedSources: FeedSource[] = []
const sources: FeedSource[] = []
const errors: unknown[] = []
for (const result of results) {
if (result.status === "fulfilled") {
feedSources.push(result.value)
sources.push(result.value)
} else {
errors.push(result.reason)
}
}
if (feedSources.length === 0 && errors.length > 0) {
if (sources.length === 0 && errors.length > 0) {
throw new AggregateError(errors, "All feed source providers failed")
}
@@ -164,6 +138,6 @@ export class UserSessionManager {
console.error("[UserSessionManager] Feed source provider failed:", error)
}
return new UserSession(userId, feedSources, this.feedEnhancer)
return new UserSession(sources, this.feedEnhancer)
}
}

View File

@@ -1,7 +1,7 @@
import type { ActionDefinition, ContextEntry, FeedItem, FeedSource } from "@aelis/core"
import { LocationSource } from "@aelis/source-location"
import { describe, expect, spyOn, test } from "bun:test"
import { describe, expect, test } from "bun:test"
import { UserSession } from "./user-session.ts"
@@ -25,10 +25,7 @@ function createStubSource(id: string, items: FeedItem[] = []): FeedSource {
describe("UserSession", () => {
test("registers sources and starts engine", async () => {
const session = new UserSession("test-user", [
createStubSource("test-a"),
createStubSource("test-b"),
])
const session = new UserSession([createStubSource("test-a"), createStubSource("test-b")])
const result = await session.engine.refresh()
@@ -37,7 +34,7 @@ describe("UserSession", () => {
test("getSource returns registered source", () => {
const location = new LocationSource()
const session = new UserSession("test-user", [location])
const session = new UserSession([location])
const result = session.getSource<LocationSource>("aelis.location")
@@ -45,13 +42,13 @@ describe("UserSession", () => {
})
test("getSource returns undefined for unknown source", () => {
const session = new UserSession("test-user", [createStubSource("test")])
const session = new UserSession([createStubSource("test")])
expect(session.getSource("unknown")).toBeUndefined()
})
test("destroy stops engine and clears sources", () => {
const session = new UserSession("test-user", [createStubSource("test")])
const session = new UserSession([createStubSource("test")])
session.destroy()
@@ -60,7 +57,7 @@ describe("UserSession", () => {
test("engine.executeAction routes to correct source", async () => {
const location = new LocationSource()
const session = new UserSession("test-user", [location])
const session = new UserSession([location])
await session.engine.executeAction("aelis.location", "update-location", {
lat: 51.5,
@@ -85,7 +82,7 @@ describe("UserSession.feed", () => {
data: { value: 42 },
},
]
const session = new UserSession("test-user", [createStubSource("test", items)])
const session = new UserSession([createStubSource("test", items)])
const result = await session.feed()
@@ -106,7 +103,7 @@ describe("UserSession.feed", () => {
const enhancer = async (feedItems: FeedItem[]) =>
feedItems.map((item) => ({ ...item, data: { ...item.data, enhanced: true } }))
const session = new UserSession("test-user", [createStubSource("test", items)], enhancer)
const session = new UserSession([createStubSource("test", items)], enhancer)
const result = await session.feed()
@@ -130,7 +127,7 @@ describe("UserSession.feed", () => {
return feedItems.map((item) => ({ ...item, data: { ...item.data, enhanced: true } }))
}
const session = new UserSession("test-user", [createStubSource("test", items)], enhancer)
const session = new UserSession([createStubSource("test", items)], enhancer)
const result1 = await session.feed()
expect(result1.items[0]!.data.enhanced).toBe(true)
@@ -165,7 +162,7 @@ describe("UserSession.feed", () => {
}))
}
const session = new UserSession("test-user", [source], enhancer)
const session = new UserSession([source], enhancer)
// First feed triggers refresh + enhancement
const result1 = await session.feed()
@@ -208,7 +205,7 @@ describe("UserSession.feed", () => {
throw new Error("enhancement exploded")
}
const session = new UserSession("test-user", [createStubSource("test", items)], enhancer)
const session = new UserSession([createStubSource("test", items)], enhancer)
const result = await session.feed()
@@ -240,7 +237,7 @@ describe("UserSession.replaceSource", () => {
]
const sourceA = createStubSource("test", itemsA)
const session = new UserSession("test-user", [sourceA])
const session = new UserSession([sourceA])
const result1 = await session.feed()
expect(result1.items).toHaveLength(1)
@@ -256,7 +253,7 @@ describe("UserSession.replaceSource", () => {
test("getSource returns new source after replace", () => {
const sourceA = createStubSource("test")
const session = new UserSession("test-user", [sourceA])
const session = new UserSession([sourceA])
const sourceB = createStubSource("test")
session.replaceSource("test", sourceB)
@@ -266,7 +263,7 @@ describe("UserSession.replaceSource", () => {
})
test("throws when replacing a source that is not registered", () => {
const session = new UserSession("test-user", [createStubSource("test")])
const session = new UserSession([createStubSource("test")])
expect(() => session.replaceSource("nonexistent", createStubSource("other"))).toThrow(
'Cannot replace source "nonexistent": not registered',
@@ -292,7 +289,7 @@ describe("UserSession.replaceSource", () => {
data: { from: "b" },
},
])
const session = new UserSession("test-user", [sourceA, sourceB])
const session = new UserSession([sourceA, sourceB])
const replacement = createStubSource("source-a", [
{
@@ -328,7 +325,7 @@ describe("UserSession.replaceSource", () => {
return feedItems.map((item) => ({ ...item, data: { ...item.data, enhanced: true } }))
}
const session = new UserSession("test-user", [createStubSource("test", items)], enhancer)
const session = new UserSession([createStubSource("test", items)], enhancer)
await session.feed()
expect(enhanceCount).toBe(1)
@@ -353,10 +350,7 @@ describe("UserSession.replaceSource", () => {
describe("UserSession.removeSource", () => {
test("removes source from engine and sources map", () => {
const session = new UserSession("test-user", [
createStubSource("test-a"),
createStubSource("test-b"),
])
const session = new UserSession([createStubSource("test-a"), createStubSource("test-b")])
session.removeSource("test-a")
@@ -374,7 +368,7 @@ describe("UserSession.removeSource", () => {
data: {},
},
]
const session = new UserSession("test-user", [createStubSource("test", items)])
const session = new UserSession([createStubSource("test", items)])
const result1 = await session.feed()
expect(result1.items).toHaveLength(1)
@@ -386,7 +380,7 @@ describe("UserSession.removeSource", () => {
})
test("is a no-op for unknown source", () => {
const session = new UserSession("test-user", [createStubSource("test")])
const session = new UserSession([createStubSource("test")])
expect(() => session.removeSource("unknown")).not.toThrow()
expect(session.getSource("test")).toBeDefined()

View File

@@ -3,7 +3,6 @@ import { FeedEngine, type FeedItem, type FeedResult, type FeedSource } from "@ae
import type { FeedEnhancer } from "../enhancement/enhance-feed.ts"
export class UserSession {
readonly userId: string
readonly engine: FeedEngine
private sources = new Map<string, FeedSource>()
private readonly enhancer: FeedEnhancer | null
@@ -13,8 +12,7 @@ export class UserSession {
private enhancingPromise: Promise<void> | null = null
private unsubscribe: (() => void) | null = null
constructor(userId: string, sources: FeedSource[], enhancer?: FeedEnhancer | null) {
this.userId = userId
constructor(sources: FeedSource[], enhancer?: FeedEnhancer | null) {
this.engine = new FeedEngine()
this.enhancer = enhancer ?? null
for (const source of sources) {
@@ -69,10 +67,6 @@ export class UserSession {
return this.sources.get(sourceId) as T | undefined
}
hasSource(sourceId: string): boolean {
return this.sources.has(sourceId)
}
/**
* Replaces a source in the engine and invalidates all caches.
* Stops and restarts the engine to re-establish reactive subscriptions.

View File

@@ -1,3 +1,21 @@
/**
* Thrown by a FeedSourceProvider when the source is not enabled for a user.
*
* UserSessionManager's Promise.allSettled handles this gracefully —
* the source is excluded from the session without crashing.
*/
export class SourceDisabledError extends Error {
readonly sourceId: string
readonly userId: string
constructor(sourceId: string, userId: string) {
super(`Source "${sourceId}" is not enabled for user "${userId}"`)
this.name = "SourceDisabledError"
this.sourceId = sourceId
this.userId = userId
}
}
/**
* Thrown when an operation targets a user source that doesn't exist.
*/

View File

@@ -1,11 +1,15 @@
import { TflSource, type ITflApi, type TflLineId } from "@aelis/source-tfl"
import { type } from "arktype"
import type { Database } from "../db/index.ts"
import type { FeedSourceProvider } from "../session/feed-source-provider.ts"
import { SourceDisabledError } from "../sources/errors.ts"
import { sources } from "../sources/user-sources.ts"
export type TflSourceProviderOptions =
| { apiKey: string; client?: never }
| { apiKey?: never; client: ITflApi }
| { db: Database; apiKey: string; client?: never }
| { db: Database; apiKey?: never; client: ITflApi }
const tflConfig = type({
"lines?": "string[]",
@@ -13,18 +17,26 @@ const tflConfig = type({
export class TflSourceProvider implements FeedSourceProvider {
readonly sourceId = "aelis.tfl"
private readonly db: Database
private readonly apiKey: string | undefined
private readonly client: ITflApi | undefined
constructor(options: TflSourceProviderOptions) {
this.db = options.db
this.apiKey = "apiKey" in options ? options.apiKey : undefined
this.client = "client" in options ? options.client : undefined
}
async feedSourceForUser(_userId: string, config: unknown): Promise<TflSource> {
const parsed = tflConfig(config)
async feedSourceForUser(userId: string): Promise<TflSource> {
const row = await sources(this.db, userId).find("aelis.tfl")
if (!row || !row.enabled) {
throw new SourceDisabledError("aelis.tfl", userId)
}
const parsed = tflConfig(row.config ?? {})
if (parsed instanceof type.errors) {
throw new Error(`Invalid TFL config: ${parsed.summary}`)
throw new Error(`Invalid TFL config for user ${userId}: ${parsed.summary}`)
}
return new TflSource({

View File

@@ -1,9 +1,14 @@
import { WeatherSource, type WeatherSourceOptions } from "@aelis/source-weatherkit"
import { type } from "arktype"
import type { Database } from "../db/index.ts"
import type { FeedSourceProvider } from "../session/feed-source-provider.ts"
import { SourceDisabledError } from "../sources/errors.ts"
import { sources } from "../sources/user-sources.ts"
export interface WeatherSourceProviderOptions {
db: Database
credentials: WeatherSourceOptions["credentials"]
client?: WeatherSourceOptions["client"]
}
@@ -16,18 +21,26 @@ const weatherConfig = type({
export class WeatherSourceProvider implements FeedSourceProvider {
readonly sourceId = "aelis.weather"
private readonly db: Database
private readonly credentials: WeatherSourceOptions["credentials"]
private readonly client: WeatherSourceOptions["client"]
constructor(options: WeatherSourceProviderOptions) {
this.db = options.db
this.credentials = options.credentials
this.client = options.client
}
async feedSourceForUser(_userId: string, config: unknown): Promise<WeatherSource> {
const parsed = weatherConfig(config)
async feedSourceForUser(userId: string): Promise<WeatherSource> {
const row = await sources(this.db, userId).find("aelis.weather")
if (!row || !row.enabled) {
throw new SourceDisabledError("aelis.weather", userId)
}
const parsed = weatherConfig(row.config ?? {})
if (parsed instanceof type.errors) {
throw new Error(`Invalid weather config: ${parsed.summary}`)
throw new Error(`Invalid weather config for user ${userId}: ${parsed.summary}`)
}
return new WeatherSource({