mirror of
https://github.com/kennethnym/aris.git
synced 2026-03-22 10:01:17 +00:00
Compare commits
2 Commits
master
...
feat/admin
| Author | SHA1 | Date | |
|---|---|---|---|
|
0f912012d6
|
|||
|
36bdf7e1bb
|
@@ -6,14 +6,3 @@ services:
|
|||||||
- postDevcontainerStart
|
- postDevcontainerStart
|
||||||
commands:
|
commands:
|
||||||
start: cd apps/aelis-client && ./scripts/run-dev-server.sh
|
start: cd apps/aelis-client && ./scripts/run-dev-server.sh
|
||||||
|
|
||||||
drizzle-studio:
|
|
||||||
name: Drizzle Studio
|
|
||||||
description: Drizzle Studio database browser for aelis-backend
|
|
||||||
triggeredBy:
|
|
||||||
- manual
|
|
||||||
commands:
|
|
||||||
start: |
|
|
||||||
FORWARD_URL=$(gitpod environment port open 4983 --name drizzle-studio-server | sed 's|https://||')
|
|
||||||
echo "Drizzle Studio: https://local.drizzle.studio/?host=${FORWARD_URL}&port=443"
|
|
||||||
cd apps/aelis-backend && bunx drizzle-kit studio --host 0.0.0.0 --port 4983
|
|
||||||
|
|||||||
@@ -1,162 +0,0 @@
|
|||||||
import type { ActionDefinition, ContextEntry, FeedItem, FeedSource } from "@aelis/core"
|
|
||||||
|
|
||||||
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"
|
|
||||||
import type { Database } from "../db/index.ts"
|
|
||||||
import type { FeedSourceProvider } from "../session/feed-source-provider.ts"
|
|
||||||
|
|
||||||
import { UserSessionManager } from "../session/user-session-manager.ts"
|
|
||||||
import { registerAdminHttpHandlers } from "./http.ts"
|
|
||||||
|
|
||||||
function createStubSource(id: string): FeedSource {
|
|
||||||
return {
|
|
||||||
id,
|
|
||||||
async listActions(): Promise<Record<string, ActionDefinition>> {
|
|
||||||
return {}
|
|
||||||
},
|
|
||||||
async executeAction(): Promise<unknown> {
|
|
||||||
return undefined
|
|
||||||
},
|
|
||||||
async fetchContext(): Promise<readonly ContextEntry[] | null> {
|
|
||||||
return null
|
|
||||||
},
|
|
||||||
async fetchItems(): Promise<FeedItem[]> {
|
|
||||||
return []
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function createStubProvider(sourceId: string): FeedSourceProvider {
|
|
||||||
return {
|
|
||||||
sourceId,
|
|
||||||
async feedSourceForUser() {
|
|
||||||
return createStubSource(sourceId)
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Passthrough admin middleware for testing (assumes admin). */
|
|
||||||
function passthroughAdminMiddleware(): AdminMiddleware {
|
|
||||||
const now = new Date()
|
|
||||||
return async (c, next) => {
|
|
||||||
c.set("user", {
|
|
||||||
id: "admin-1",
|
|
||||||
name: "Admin",
|
|
||||||
email: "admin@test.com",
|
|
||||||
emailVerified: true,
|
|
||||||
image: null,
|
|
||||||
createdAt: now,
|
|
||||||
updatedAt: now,
|
|
||||||
role: "admin",
|
|
||||||
banned: false,
|
|
||||||
banReason: null,
|
|
||||||
banExpires: null,
|
|
||||||
} as AuthUser)
|
|
||||||
c.set("session", { id: "sess-1" } as AuthSession)
|
|
||||||
await next()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const fakeDb = {} as Database
|
|
||||||
|
|
||||||
function createApp(providers: FeedSourceProvider[]) {
|
|
||||||
const sessionManager = new UserSessionManager({ providers })
|
|
||||||
const app = new Hono()
|
|
||||||
registerAdminHttpHandlers(app, {
|
|
||||||
sessionManager,
|
|
||||||
adminMiddleware: passthroughAdminMiddleware(),
|
|
||||||
db: fakeDb,
|
|
||||||
})
|
|
||||||
return { app, sessionManager }
|
|
||||||
}
|
|
||||||
|
|
||||||
const validWeatherConfig = {
|
|
||||||
credentials: {
|
|
||||||
privateKey: "pk-123",
|
|
||||||
keyId: "key-456",
|
|
||||||
teamId: "team-789",
|
|
||||||
serviceId: "svc-abc",
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
describe("PUT /api/admin/:sourceId/config", () => {
|
|
||||||
test("returns 404 for unknown provider", async () => {
|
|
||||||
const { app } = createApp([createStubProvider("aelis.location")])
|
|
||||||
|
|
||||||
const res = await app.request("/api/admin/aelis.nonexistent/config", {
|
|
||||||
method: "PUT",
|
|
||||||
headers: { "Content-Type": "application/json" },
|
|
||||||
body: JSON.stringify({ key: "value" }),
|
|
||||||
})
|
|
||||||
|
|
||||||
expect(res.status).toBe(404)
|
|
||||||
const body = (await res.json()) as { error: string }
|
|
||||||
expect(body.error).toContain("not found")
|
|
||||||
})
|
|
||||||
|
|
||||||
test("returns 404 for provider without runtime config support", async () => {
|
|
||||||
const { app } = createApp([createStubProvider("aelis.location")])
|
|
||||||
|
|
||||||
const res = await app.request("/api/admin/aelis.location/config", {
|
|
||||||
method: "PUT",
|
|
||||||
headers: { "Content-Type": "application/json" },
|
|
||||||
body: JSON.stringify({ key: "value" }),
|
|
||||||
})
|
|
||||||
|
|
||||||
expect(res.status).toBe(404)
|
|
||||||
const body = (await res.json()) as { error: string }
|
|
||||||
expect(body.error).toContain("not found")
|
|
||||||
})
|
|
||||||
|
|
||||||
test("returns 400 for invalid JSON body", async () => {
|
|
||||||
const { app } = createApp([createStubProvider("aelis.weather")])
|
|
||||||
|
|
||||||
const res = await app.request("/api/admin/aelis.weather/config", {
|
|
||||||
method: "PUT",
|
|
||||||
headers: { "Content-Type": "application/json" },
|
|
||||||
body: "not json",
|
|
||||||
})
|
|
||||||
|
|
||||||
expect(res.status).toBe(400)
|
|
||||||
const body = (await res.json()) as { error: string }
|
|
||||||
expect(body.error).toContain("Invalid JSON")
|
|
||||||
})
|
|
||||||
|
|
||||||
test("returns 400 when weather config fails validation", async () => {
|
|
||||||
const { app } = createApp([createStubProvider("aelis.weather")])
|
|
||||||
|
|
||||||
const res = await app.request("/api/admin/aelis.weather/config", {
|
|
||||||
method: "PUT",
|
|
||||||
headers: { "Content-Type": "application/json" },
|
|
||||||
body: JSON.stringify({ credentials: { privateKey: 123 } }),
|
|
||||||
})
|
|
||||||
|
|
||||||
expect(res.status).toBe(400)
|
|
||||||
const body = (await res.json()) as { error: string }
|
|
||||||
expect(body.error).toBeDefined()
|
|
||||||
})
|
|
||||||
|
|
||||||
test("returns 204 and applies valid weather config", async () => {
|
|
||||||
const { app, sessionManager } = createApp([createStubProvider("aelis.weather")])
|
|
||||||
|
|
||||||
const originalProvider = sessionManager.getProvider("aelis.weather")
|
|
||||||
|
|
||||||
const res = await app.request("/api/admin/aelis.weather/config", {
|
|
||||||
method: "PUT",
|
|
||||||
headers: { "Content-Type": "application/json" },
|
|
||||||
body: JSON.stringify(validWeatherConfig),
|
|
||||||
})
|
|
||||||
|
|
||||||
expect(res.status).toBe(204)
|
|
||||||
|
|
||||||
// Provider was replaced with a new instance
|
|
||||||
const provider = sessionManager.getProvider("aelis.weather")
|
|
||||||
expect(provider).toBeDefined()
|
|
||||||
expect(provider!.sourceId).toBe("aelis.weather")
|
|
||||||
expect(provider).not.toBe(originalProvider)
|
|
||||||
})
|
|
||||||
|
|
||||||
})
|
|
||||||
@@ -1,88 +0,0 @@
|
|||||||
import type { Context, Hono } from "hono"
|
|
||||||
|
|
||||||
import { type } from "arktype"
|
|
||||||
import { createMiddleware } from "hono/factory"
|
|
||||||
|
|
||||||
import type { AdminMiddleware } from "../auth/admin-middleware.ts"
|
|
||||||
import type { Database } from "../db/index.ts"
|
|
||||||
import type { UserSessionManager } from "../session/index.ts"
|
|
||||||
|
|
||||||
import { WeatherSourceProvider } from "../weather/provider.ts"
|
|
||||||
|
|
||||||
type Env = {
|
|
||||||
Variables: {
|
|
||||||
sessionManager: UserSessionManager
|
|
||||||
db: Database
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
interface AdminHttpHandlersDeps {
|
|
||||||
sessionManager: UserSessionManager
|
|
||||||
adminMiddleware: AdminMiddleware
|
|
||||||
db: Database
|
|
||||||
}
|
|
||||||
|
|
||||||
export function registerAdminHttpHandlers(
|
|
||||||
app: Hono,
|
|
||||||
{ sessionManager, adminMiddleware, db }: AdminHttpHandlersDeps,
|
|
||||||
) {
|
|
||||||
const inject = createMiddleware<Env>(async (c, next) => {
|
|
||||||
c.set("sessionManager", sessionManager)
|
|
||||||
c.set("db", db)
|
|
||||||
await next()
|
|
||||||
})
|
|
||||||
|
|
||||||
app.put("/api/admin/:sourceId/config", inject, adminMiddleware, handleUpdateProviderConfig)
|
|
||||||
}
|
|
||||||
|
|
||||||
const WeatherKitSourceProviderConfig = type({
|
|
||||||
credentials: {
|
|
||||||
privateKey: "string",
|
|
||||||
keyId: "string",
|
|
||||||
teamId: "string",
|
|
||||||
serviceId: "string",
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
async function handleUpdateProviderConfig(c: Context<Env>) {
|
|
||||||
const sourceId = c.req.param("sourceId")
|
|
||||||
if (!sourceId) {
|
|
||||||
return c.body(null, 404)
|
|
||||||
}
|
|
||||||
|
|
||||||
const sessionManager = c.get("sessionManager")
|
|
||||||
const db = c.get("db")
|
|
||||||
|
|
||||||
let body: unknown
|
|
||||||
try {
|
|
||||||
body = await c.req.json()
|
|
||||||
} catch {
|
|
||||||
return c.json({ error: "Invalid JSON" }, 400)
|
|
||||||
}
|
|
||||||
|
|
||||||
switch (sourceId) {
|
|
||||||
case "aelis.weather": {
|
|
||||||
const parsed = WeatherKitSourceProviderConfig(body)
|
|
||||||
if (parsed instanceof type.errors) {
|
|
||||||
return c.json({ error: parsed.summary }, 400)
|
|
||||||
}
|
|
||||||
|
|
||||||
const updated = new WeatherSourceProvider({
|
|
||||||
db,
|
|
||||||
credentials: parsed.credentials,
|
|
||||||
})
|
|
||||||
|
|
||||||
try {
|
|
||||||
await sessionManager.replaceProvider(updated)
|
|
||||||
} catch (err) {
|
|
||||||
console.error(`[admin] replaceProvider("${sourceId}") failed:`, err)
|
|
||||||
return c.json({ error: "Failed to apply config" }, 500)
|
|
||||||
}
|
|
||||||
|
|
||||||
return c.body(null, 204)
|
|
||||||
}
|
|
||||||
|
|
||||||
default:
|
|
||||||
return c.json({ error: `Provider "${sourceId}" not found` }, 404)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,95 +0,0 @@
|
|||||||
import { Hono } from "hono"
|
|
||||||
import { describe, expect, test } from "bun:test"
|
|
||||||
|
|
||||||
import type { Auth } from "./index.ts"
|
|
||||||
import type { AuthSession, AuthUser } from "./session.ts"
|
|
||||||
|
|
||||||
import { createRequireAdmin } from "./admin-middleware.ts"
|
|
||||||
|
|
||||||
function makeUser(role: string | null): AuthUser {
|
|
||||||
const now = new Date()
|
|
||||||
return {
|
|
||||||
id: "user-1",
|
|
||||||
name: "Test User",
|
|
||||||
email: "test@example.com",
|
|
||||||
emailVerified: true,
|
|
||||||
image: null,
|
|
||||||
createdAt: now,
|
|
||||||
updatedAt: now,
|
|
||||||
role,
|
|
||||||
banned: false,
|
|
||||||
banReason: null,
|
|
||||||
banExpires: null,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function makeSession(): AuthSession {
|
|
||||||
const now = new Date()
|
|
||||||
return {
|
|
||||||
id: "sess-1",
|
|
||||||
userId: "user-1",
|
|
||||||
token: "tok-1",
|
|
||||||
expiresAt: new Date(now.getTime() + 7 * 24 * 60 * 60 * 1000),
|
|
||||||
ipAddress: "127.0.0.1",
|
|
||||||
userAgent: "test",
|
|
||||||
createdAt: now,
|
|
||||||
updatedAt: now,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function mockAuth(sessionResult: { user: AuthUser; session: AuthSession } | null): Auth {
|
|
||||||
return {
|
|
||||||
api: {
|
|
||||||
getSession: async () => sessionResult,
|
|
||||||
},
|
|
||||||
} as unknown as Auth
|
|
||||||
}
|
|
||||||
|
|
||||||
function createApp(auth: Auth) {
|
|
||||||
const app = new Hono()
|
|
||||||
const middleware = createRequireAdmin(auth)
|
|
||||||
app.get("/api/admin/test", middleware, (c) => c.json({ ok: true }))
|
|
||||||
return app
|
|
||||||
}
|
|
||||||
|
|
||||||
describe("createRequireAdmin", () => {
|
|
||||||
test("returns 401 when no session", async () => {
|
|
||||||
const app = createApp(mockAuth(null))
|
|
||||||
|
|
||||||
const res = await app.request("/api/admin/test")
|
|
||||||
|
|
||||||
expect(res.status).toBe(401)
|
|
||||||
const body = (await res.json()) as { error: string }
|
|
||||||
expect(body.error).toBe("Unauthorized")
|
|
||||||
})
|
|
||||||
|
|
||||||
test("returns 403 when user is not admin", async () => {
|
|
||||||
const app = createApp(mockAuth({ user: makeUser("user"), session: makeSession() }))
|
|
||||||
|
|
||||||
const res = await app.request("/api/admin/test")
|
|
||||||
|
|
||||||
expect(res.status).toBe(403)
|
|
||||||
const body = (await res.json()) as { error: string }
|
|
||||||
expect(body.error).toBe("Forbidden")
|
|
||||||
})
|
|
||||||
|
|
||||||
test("returns 403 when role is null", async () => {
|
|
||||||
const app = createApp(mockAuth({ user: makeUser(null), session: makeSession() }))
|
|
||||||
|
|
||||||
const res = await app.request("/api/admin/test")
|
|
||||||
|
|
||||||
expect(res.status).toBe(403)
|
|
||||||
})
|
|
||||||
|
|
||||||
test("allows admin users through and sets context", async () => {
|
|
||||||
const user = makeUser("admin")
|
|
||||||
const session = makeSession()
|
|
||||||
const app = createApp(mockAuth({ user, session }))
|
|
||||||
|
|
||||||
const res = await app.request("/api/admin/test")
|
|
||||||
|
|
||||||
expect(res.status).toBe(200)
|
|
||||||
const body = (await res.json()) as { ok: boolean }
|
|
||||||
expect(body.ok).toBe(true)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
@@ -1,28 +0,0 @@
|
|||||||
import type { Context, MiddlewareHandler, Next } from "hono"
|
|
||||||
|
|
||||||
import type { Auth } from "./index.ts"
|
|
||||||
import type { AuthSessionEnv } from "./session-middleware.ts"
|
|
||||||
|
|
||||||
export type AdminMiddleware = MiddlewareHandler<AuthSessionEnv>
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Creates a middleware that requires a valid session with admin role.
|
|
||||||
* Returns 401 if not authenticated, 403 if not admin.
|
|
||||||
*/
|
|
||||||
export function createRequireAdmin(auth: Auth): AdminMiddleware {
|
|
||||||
return async (c: Context, next: Next): Promise<Response | void> => {
|
|
||||||
const session = await auth.api.getSession({ headers: c.req.raw.headers })
|
|
||||||
|
|
||||||
if (!session) {
|
|
||||||
return c.json({ error: "Unauthorized" }, 401)
|
|
||||||
}
|
|
||||||
|
|
||||||
if (session.user.role !== "admin") {
|
|
||||||
return c.json({ error: "Forbidden" }, 403)
|
|
||||||
}
|
|
||||||
|
|
||||||
c.set("user", session.user)
|
|
||||||
c.set("session", session.session)
|
|
||||||
await next()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -72,14 +72,7 @@ describe("GET /api/feed", () => {
|
|||||||
},
|
},
|
||||||
]
|
]
|
||||||
const manager = new UserSessionManager({
|
const manager = new UserSessionManager({
|
||||||
providers: [
|
providers: [async () => createStubSource("test", items)],
|
||||||
{
|
|
||||||
sourceId: "test",
|
|
||||||
async feedSourceForUser() {
|
|
||||||
return createStubSource("test", items)
|
|
||||||
},
|
|
||||||
},
|
|
||||||
],
|
|
||||||
})
|
})
|
||||||
const app = buildTestApp(manager, "user-1")
|
const app = buildTestApp(manager, "user-1")
|
||||||
|
|
||||||
@@ -112,14 +105,7 @@ describe("GET /api/feed", () => {
|
|||||||
},
|
},
|
||||||
]
|
]
|
||||||
const manager = new UserSessionManager({
|
const manager = new UserSessionManager({
|
||||||
providers: [
|
providers: [async () => createStubSource("test", items)],
|
||||||
{
|
|
||||||
sourceId: "test",
|
|
||||||
async feedSourceForUser() {
|
|
||||||
return createStubSource("test", items)
|
|
||||||
},
|
|
||||||
},
|
|
||||||
],
|
|
||||||
})
|
})
|
||||||
const app = buildTestApp(manager, "user-1")
|
const app = buildTestApp(manager, "user-1")
|
||||||
|
|
||||||
@@ -150,16 +136,7 @@ describe("GET /api/feed", () => {
|
|||||||
throw new Error("connection timeout")
|
throw new Error("connection timeout")
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
const manager = new UserSessionManager({
|
const manager = new UserSessionManager({ providers: [async () => failingSource] })
|
||||||
providers: [
|
|
||||||
{
|
|
||||||
sourceId: "failing",
|
|
||||||
async feedSourceForUser() {
|
|
||||||
return failingSource
|
|
||||||
},
|
|
||||||
},
|
|
||||||
],
|
|
||||||
})
|
|
||||||
const app = buildTestApp(manager, "user-1")
|
const app = buildTestApp(manager, "user-1")
|
||||||
|
|
||||||
const res = await app.request("/api/feed")
|
const res = await app.request("/api/feed")
|
||||||
@@ -175,11 +152,8 @@ describe("GET /api/feed", () => {
|
|||||||
test("returns 503 when all providers fail", async () => {
|
test("returns 503 when all providers fail", async () => {
|
||||||
const manager = new UserSessionManager({
|
const manager = new UserSessionManager({
|
||||||
providers: [
|
providers: [
|
||||||
{
|
async () => {
|
||||||
sourceId: "test",
|
throw new Error("provider down")
|
||||||
async feedSourceForUser() {
|
|
||||||
throw new Error("provider down")
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
})
|
})
|
||||||
@@ -207,14 +181,7 @@ describe("GET /api/context", () => {
|
|||||||
|
|
||||||
async function buildContextApp(userId?: string) {
|
async function buildContextApp(userId?: string) {
|
||||||
const manager = new UserSessionManager({
|
const manager = new UserSessionManager({
|
||||||
providers: [
|
providers: [async () => createStubSource("weather", [], contextEntries)],
|
||||||
{
|
|
||||||
sourceId: "weather",
|
|
||||||
async feedSourceForUser() {
|
|
||||||
return createStubSource("weather", [], contextEntries)
|
|
||||||
},
|
|
||||||
},
|
|
||||||
],
|
|
||||||
})
|
})
|
||||||
const app = buildTestApp(manager, userId)
|
const app = buildTestApp(manager, userId)
|
||||||
const session = await manager.getOrCreate(mockUserId)
|
const session = await manager.getOrCreate(mockUserId)
|
||||||
|
|||||||
@@ -7,7 +7,6 @@ import { SourceDisabledError } from "../sources/errors.ts"
|
|||||||
import { sources } from "../sources/user-sources.ts"
|
import { sources } from "../sources/user-sources.ts"
|
||||||
|
|
||||||
export class LocationSourceProvider implements FeedSourceProvider {
|
export class LocationSourceProvider implements FeedSourceProvider {
|
||||||
readonly sourceId = "aelis.location"
|
|
||||||
private readonly db: Database
|
private readonly db: Database
|
||||||
|
|
||||||
constructor(db: Database) {
|
constructor(db: Database) {
|
||||||
|
|||||||
@@ -1,7 +1,5 @@
|
|||||||
import { Hono } from "hono"
|
import { Hono } from "hono"
|
||||||
|
|
||||||
import { registerAdminHttpHandlers } from "./admin/http.ts"
|
|
||||||
import { createRequireAdmin } from "./auth/admin-middleware.ts"
|
|
||||||
import { registerAuthHandlers } from "./auth/http.ts"
|
import { registerAuthHandlers } from "./auth/http.ts"
|
||||||
import { createAuth } from "./auth/index.ts"
|
import { createAuth } from "./auth/index.ts"
|
||||||
import { createRequireSession } from "./auth/session-middleware.ts"
|
import { createRequireSession } from "./auth/session-middleware.ts"
|
||||||
@@ -52,7 +50,6 @@ function main() {
|
|||||||
app.get("/health", (c) => c.json({ status: "ok" }))
|
app.get("/health", (c) => c.json({ status: "ok" }))
|
||||||
|
|
||||||
const authSessionMiddleware = createRequireSession(auth)
|
const authSessionMiddleware = createRequireSession(auth)
|
||||||
const adminMiddleware = createRequireAdmin(auth)
|
|
||||||
|
|
||||||
registerAuthHandlers(app, auth)
|
registerAuthHandlers(app, auth)
|
||||||
|
|
||||||
@@ -61,7 +58,6 @@ function main() {
|
|||||||
authSessionMiddleware,
|
authSessionMiddleware,
|
||||||
})
|
})
|
||||||
registerLocationHttpHandlers(app, { sessionManager, authSessionMiddleware })
|
registerLocationHttpHandlers(app, { sessionManager, authSessionMiddleware })
|
||||||
registerAdminHttpHandlers(app, { sessionManager, adminMiddleware, db })
|
|
||||||
|
|
||||||
process.on("SIGTERM", async () => {
|
process.on("SIGTERM", async () => {
|
||||||
await closeDb()
|
await closeDb()
|
||||||
|
|||||||
@@ -1,7 +1,9 @@
|
|||||||
import type { FeedSource } from "@aelis/core"
|
import type { FeedSource } from "@aelis/core"
|
||||||
|
|
||||||
export interface FeedSourceProvider {
|
export interface FeedSourceProvider {
|
||||||
/** The source ID this provider is responsible for (e.g., "aelis.location"). */
|
|
||||||
readonly sourceId: string
|
|
||||||
feedSourceForUser(userId: string): Promise<FeedSource>
|
feedSourceForUser(userId: string): Promise<FeedSource>
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type FeedSourceProviderFn = (userId: string) => Promise<FeedSource>
|
||||||
|
|
||||||
|
export type FeedSourceProviderInput = FeedSourceProvider | FeedSourceProviderFn
|
||||||
|
|||||||
@@ -1,3 +1,7 @@
|
|||||||
export type { FeedSourceProvider } from "./feed-source-provider.ts"
|
export type {
|
||||||
|
FeedSourceProvider,
|
||||||
|
FeedSourceProviderFn,
|
||||||
|
FeedSourceProviderInput,
|
||||||
|
} from "./feed-source-provider.ts"
|
||||||
export { UserSession } from "./user-session.ts"
|
export { UserSession } from "./user-session.ts"
|
||||||
export { UserSessionManager } from "./user-session-manager.ts"
|
export { UserSessionManager } from "./user-session-manager.ts"
|
||||||
|
|||||||
@@ -1,55 +1,15 @@
|
|||||||
import type { ActionDefinition, ContextEntry, FeedItem, FeedSource } from "@aelis/core"
|
|
||||||
|
|
||||||
import { LocationSource } from "@aelis/source-location"
|
import { LocationSource } from "@aelis/source-location"
|
||||||
import { WeatherSource } from "@aelis/source-weatherkit"
|
import { WeatherSource } from "@aelis/source-weatherkit"
|
||||||
import { describe, expect, mock, spyOn, test } from "bun:test"
|
import { describe, expect, mock, spyOn, test } from "bun:test"
|
||||||
|
|
||||||
import type { FeedSourceProvider } from "./feed-source-provider.ts"
|
|
||||||
|
|
||||||
import { UserSessionManager } from "./user-session-manager.ts"
|
import { UserSessionManager } from "./user-session-manager.ts"
|
||||||
|
|
||||||
function createStubSource(id: string, items: FeedItem[] = []): FeedSource {
|
const mockWeatherProvider = async () =>
|
||||||
return {
|
new WeatherSource({ client: { fetch: async () => ({}) as never } })
|
||||||
id,
|
|
||||||
async listActions(): Promise<Record<string, ActionDefinition>> {
|
|
||||||
return {}
|
|
||||||
},
|
|
||||||
async executeAction(): Promise<unknown> {
|
|
||||||
return undefined
|
|
||||||
},
|
|
||||||
async fetchContext(): Promise<readonly ContextEntry[] | null> {
|
|
||||||
return null
|
|
||||||
},
|
|
||||||
async fetchItems() {
|
|
||||||
return items
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function createStubProvider(
|
|
||||||
sourceId: string,
|
|
||||||
factory: (userId: string) => Promise<FeedSource> = async () => createStubSource(sourceId),
|
|
||||||
): FeedSourceProvider {
|
|
||||||
return { sourceId, feedSourceForUser: factory }
|
|
||||||
}
|
|
||||||
|
|
||||||
const locationProvider: FeedSourceProvider = {
|
|
||||||
sourceId: "aelis.location",
|
|
||||||
async feedSourceForUser() {
|
|
||||||
return new LocationSource()
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
const weatherProvider: FeedSourceProvider = {
|
|
||||||
sourceId: "aelis.weather",
|
|
||||||
async feedSourceForUser() {
|
|
||||||
return new WeatherSource({ client: { fetch: async () => ({}) as never } })
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
describe("UserSessionManager", () => {
|
describe("UserSessionManager", () => {
|
||||||
test("getOrCreate creates session on first call", async () => {
|
test("getOrCreate creates session on first call", async () => {
|
||||||
const manager = new UserSessionManager({ providers: [locationProvider] })
|
const manager = new UserSessionManager({ providers: [async () => new LocationSource()] })
|
||||||
|
|
||||||
const session = await manager.getOrCreate("user-1")
|
const session = await manager.getOrCreate("user-1")
|
||||||
|
|
||||||
@@ -58,7 +18,7 @@ describe("UserSessionManager", () => {
|
|||||||
})
|
})
|
||||||
|
|
||||||
test("getOrCreate returns same session for same user", async () => {
|
test("getOrCreate returns same session for same user", async () => {
|
||||||
const manager = new UserSessionManager({ providers: [locationProvider] })
|
const manager = new UserSessionManager({ providers: [async () => new LocationSource()] })
|
||||||
|
|
||||||
const session1 = await manager.getOrCreate("user-1")
|
const session1 = await manager.getOrCreate("user-1")
|
||||||
const session2 = await manager.getOrCreate("user-1")
|
const session2 = await manager.getOrCreate("user-1")
|
||||||
@@ -67,7 +27,7 @@ describe("UserSessionManager", () => {
|
|||||||
})
|
})
|
||||||
|
|
||||||
test("getOrCreate returns different sessions for different users", async () => {
|
test("getOrCreate returns different sessions for different users", async () => {
|
||||||
const manager = new UserSessionManager({ providers: [locationProvider] })
|
const manager = new UserSessionManager({ providers: [async () => new LocationSource()] })
|
||||||
|
|
||||||
const session1 = await manager.getOrCreate("user-1")
|
const session1 = await manager.getOrCreate("user-1")
|
||||||
const session2 = await manager.getOrCreate("user-2")
|
const session2 = await manager.getOrCreate("user-2")
|
||||||
@@ -76,7 +36,7 @@ describe("UserSessionManager", () => {
|
|||||||
})
|
})
|
||||||
|
|
||||||
test("each user gets independent source instances", async () => {
|
test("each user gets independent source instances", async () => {
|
||||||
const manager = new UserSessionManager({ providers: [locationProvider] })
|
const manager = new UserSessionManager({ providers: [async () => new LocationSource()] })
|
||||||
|
|
||||||
const session1 = await manager.getOrCreate("user-1")
|
const session1 = await manager.getOrCreate("user-1")
|
||||||
const session2 = await manager.getOrCreate("user-2")
|
const session2 = await manager.getOrCreate("user-2")
|
||||||
@@ -88,7 +48,7 @@ describe("UserSessionManager", () => {
|
|||||||
})
|
})
|
||||||
|
|
||||||
test("remove destroys session and allows re-creation", async () => {
|
test("remove destroys session and allows re-creation", async () => {
|
||||||
const manager = new UserSessionManager({ providers: [locationProvider] })
|
const manager = new UserSessionManager({ providers: [async () => new LocationSource()] })
|
||||||
|
|
||||||
const session1 = await manager.getOrCreate("user-1")
|
const session1 = await manager.getOrCreate("user-1")
|
||||||
manager.remove("user-1")
|
manager.remove("user-1")
|
||||||
@@ -98,14 +58,33 @@ describe("UserSessionManager", () => {
|
|||||||
})
|
})
|
||||||
|
|
||||||
test("remove is no-op for unknown user", () => {
|
test("remove is no-op for unknown user", () => {
|
||||||
const manager = new UserSessionManager({ providers: [locationProvider] })
|
const manager = new UserSessionManager({ providers: [async () => new LocationSource()] })
|
||||||
|
|
||||||
expect(() => manager.remove("unknown")).not.toThrow()
|
expect(() => manager.remove("unknown")).not.toThrow()
|
||||||
})
|
})
|
||||||
|
|
||||||
test("registers multiple providers", async () => {
|
test("accepts function providers", async () => {
|
||||||
|
const manager = new UserSessionManager({ providers: [async () => new LocationSource()] })
|
||||||
|
|
||||||
|
const session = await manager.getOrCreate("user-1")
|
||||||
|
const result = await session.engine.refresh()
|
||||||
|
|
||||||
|
expect(result.errors).toHaveLength(0)
|
||||||
|
})
|
||||||
|
|
||||||
|
test("accepts object providers", async () => {
|
||||||
const manager = new UserSessionManager({
|
const manager = new UserSessionManager({
|
||||||
providers: [locationProvider, weatherProvider],
|
providers: [async () => new LocationSource(), mockWeatherProvider],
|
||||||
|
})
|
||||||
|
|
||||||
|
const session = await manager.getOrCreate("user-1")
|
||||||
|
|
||||||
|
expect(session.getSource("aelis.weather")).toBeDefined()
|
||||||
|
})
|
||||||
|
|
||||||
|
test("accepts mixed providers", async () => {
|
||||||
|
const manager = new UserSessionManager({
|
||||||
|
providers: [async () => new LocationSource(), mockWeatherProvider],
|
||||||
})
|
})
|
||||||
|
|
||||||
const session = await manager.getOrCreate("user-1")
|
const session = await manager.getOrCreate("user-1")
|
||||||
@@ -115,7 +94,7 @@ describe("UserSessionManager", () => {
|
|||||||
})
|
})
|
||||||
|
|
||||||
test("refresh returns feed result through session", async () => {
|
test("refresh returns feed result through session", async () => {
|
||||||
const manager = new UserSessionManager({ providers: [locationProvider] })
|
const manager = new UserSessionManager({ providers: [async () => new LocationSource()] })
|
||||||
|
|
||||||
const session = await manager.getOrCreate("user-1")
|
const session = await manager.getOrCreate("user-1")
|
||||||
const result = await session.engine.refresh()
|
const result = await session.engine.refresh()
|
||||||
@@ -127,7 +106,7 @@ describe("UserSessionManager", () => {
|
|||||||
})
|
})
|
||||||
|
|
||||||
test("location update via executeAction works", async () => {
|
test("location update via executeAction works", async () => {
|
||||||
const manager = new UserSessionManager({ providers: [locationProvider] })
|
const manager = new UserSessionManager({ providers: [async () => new LocationSource()] })
|
||||||
|
|
||||||
const session = await manager.getOrCreate("user-1")
|
const session = await manager.getOrCreate("user-1")
|
||||||
await session.engine.executeAction("aelis.location", "update-location", {
|
await session.engine.executeAction("aelis.location", "update-location", {
|
||||||
@@ -142,7 +121,7 @@ describe("UserSessionManager", () => {
|
|||||||
})
|
})
|
||||||
|
|
||||||
test("subscribe receives updates after location push", async () => {
|
test("subscribe receives updates after location push", async () => {
|
||||||
const manager = new UserSessionManager({ providers: [locationProvider] })
|
const manager = new UserSessionManager({ providers: [async () => new LocationSource()] })
|
||||||
const callback = mock()
|
const callback = mock()
|
||||||
|
|
||||||
const session = await manager.getOrCreate("user-1")
|
const session = await manager.getOrCreate("user-1")
|
||||||
@@ -162,7 +141,7 @@ describe("UserSessionManager", () => {
|
|||||||
})
|
})
|
||||||
|
|
||||||
test("remove stops reactive updates", async () => {
|
test("remove stops reactive updates", async () => {
|
||||||
const manager = new UserSessionManager({ providers: [locationProvider] })
|
const manager = new UserSessionManager({ providers: [async () => new LocationSource()] })
|
||||||
const callback = mock()
|
const callback = mock()
|
||||||
|
|
||||||
const session = await manager.getOrCreate("user-1")
|
const session = await manager.getOrCreate("user-1")
|
||||||
@@ -185,15 +164,13 @@ describe("UserSessionManager", () => {
|
|||||||
})
|
})
|
||||||
|
|
||||||
test("creates session with successful providers when some fail", async () => {
|
test("creates session with successful providers when some fail", async () => {
|
||||||
const failingProvider: FeedSourceProvider = {
|
|
||||||
sourceId: "aelis.failing",
|
|
||||||
async feedSourceForUser() {
|
|
||||||
throw new Error("provider failed")
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
const manager = new UserSessionManager({
|
const manager = new UserSessionManager({
|
||||||
providers: [locationProvider, failingProvider],
|
providers: [
|
||||||
|
async () => new LocationSource(),
|
||||||
|
async () => {
|
||||||
|
throw new Error("provider failed")
|
||||||
|
},
|
||||||
|
],
|
||||||
})
|
})
|
||||||
|
|
||||||
const spy = spyOn(console, "error").mockImplementation(() => {})
|
const spy = spyOn(console, "error").mockImplementation(() => {})
|
||||||
@@ -210,17 +187,11 @@ describe("UserSessionManager", () => {
|
|||||||
test("throws AggregateError when all providers fail", async () => {
|
test("throws AggregateError when all providers fail", async () => {
|
||||||
const manager = new UserSessionManager({
|
const manager = new UserSessionManager({
|
||||||
providers: [
|
providers: [
|
||||||
{
|
async () => {
|
||||||
sourceId: "aelis.fail-1",
|
throw new Error("first failed")
|
||||||
async feedSourceForUser() {
|
|
||||||
throw new Error("first failed")
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
{
|
async () => {
|
||||||
sourceId: "aelis.fail-2",
|
throw new Error("second failed")
|
||||||
async feedSourceForUser() {
|
|
||||||
throw new Error("second failed")
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
})
|
})
|
||||||
@@ -232,13 +203,11 @@ describe("UserSessionManager", () => {
|
|||||||
let callCount = 0
|
let callCount = 0
|
||||||
const manager = new UserSessionManager({
|
const manager = new UserSessionManager({
|
||||||
providers: [
|
providers: [
|
||||||
{
|
async () => {
|
||||||
sourceId: "aelis.location",
|
callCount++
|
||||||
async feedSourceForUser() {
|
// Simulate async work to widen the race window
|
||||||
callCount++
|
await new Promise((resolve) => setTimeout(resolve, 10))
|
||||||
await new Promise((resolve) => setTimeout(resolve, 10))
|
return new LocationSource()
|
||||||
return new LocationSource()
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
})
|
})
|
||||||
@@ -260,12 +229,9 @@ describe("UserSessionManager", () => {
|
|||||||
|
|
||||||
const manager = new UserSessionManager({
|
const manager = new UserSessionManager({
|
||||||
providers: [
|
providers: [
|
||||||
{
|
async () => {
|
||||||
sourceId: "aelis.location",
|
await providerGate
|
||||||
async feedSourceForUser() {
|
return new LocationSource()
|
||||||
await providerGate
|
|
||||||
return new LocationSource()
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
})
|
})
|
||||||
@@ -286,205 +252,3 @@ describe("UserSessionManager", () => {
|
|||||||
expect(freshSession.engine).toBeDefined()
|
expect(freshSession.engine).toBeDefined()
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
describe("UserSessionManager.replaceProvider", () => {
|
|
||||||
test("replaces source in all active sessions", async () => {
|
|
||||||
const itemsV1: FeedItem[] = [
|
|
||||||
{
|
|
||||||
id: "v1",
|
|
||||||
sourceId: "test",
|
|
||||||
type: "test",
|
|
||||||
timestamp: new Date(),
|
|
||||||
data: { version: 1 },
|
|
||||||
},
|
|
||||||
]
|
|
||||||
const itemsV2: FeedItem[] = [
|
|
||||||
{
|
|
||||||
id: "v2",
|
|
||||||
sourceId: "test",
|
|
||||||
type: "test",
|
|
||||||
timestamp: new Date(),
|
|
||||||
data: { version: 2 },
|
|
||||||
},
|
|
||||||
]
|
|
||||||
|
|
||||||
const providerV1 = createStubProvider("test", async () => createStubSource("test", itemsV1))
|
|
||||||
const manager = new UserSessionManager({ providers: [providerV1] })
|
|
||||||
|
|
||||||
const session1 = await manager.getOrCreate("user-1")
|
|
||||||
const session2 = await manager.getOrCreate("user-2")
|
|
||||||
|
|
||||||
// Verify v1 items
|
|
||||||
const feed1 = await session1.feed()
|
|
||||||
expect(feed1.items[0]!.data.version).toBe(1)
|
|
||||||
|
|
||||||
// Replace provider
|
|
||||||
const providerV2 = createStubProvider("test", async () => createStubSource("test", itemsV2))
|
|
||||||
await manager.replaceProvider(providerV2)
|
|
||||||
|
|
||||||
// Both sessions should now serve v2 items
|
|
||||||
const feed1After = await session1.feed()
|
|
||||||
const feed2After = await session2.feed()
|
|
||||||
expect(feed1After.items[0]!.data.version).toBe(2)
|
|
||||||
expect(feed2After.items[0]!.data.version).toBe(2)
|
|
||||||
})
|
|
||||||
|
|
||||||
test("throws for unknown provider sourceId", async () => {
|
|
||||||
const manager = new UserSessionManager({ providers: [locationProvider] })
|
|
||||||
|
|
||||||
const unknownProvider = createStubProvider("aelis.unknown")
|
|
||||||
|
|
||||||
await expect(manager.replaceProvider(unknownProvider)).rejects.toThrow(
|
|
||||||
"no existing provider with that sourceId",
|
|
||||||
)
|
|
||||||
})
|
|
||||||
|
|
||||||
test("keeps existing source when new provider fails for a user", async () => {
|
|
||||||
const providerV1 = createStubProvider("test", async () => createStubSource("test"))
|
|
||||||
const manager = new UserSessionManager({ providers: [providerV1] })
|
|
||||||
|
|
||||||
const session = await manager.getOrCreate("user-1")
|
|
||||||
expect(session.getSource("test")).toBeDefined()
|
|
||||||
|
|
||||||
const spy = spyOn(console, "error").mockImplementation(() => {})
|
|
||||||
|
|
||||||
const failingProvider = createStubProvider("test", async () => {
|
|
||||||
throw new Error("source disabled")
|
|
||||||
})
|
|
||||||
await manager.replaceProvider(failingProvider)
|
|
||||||
|
|
||||||
expect(session.getSource("test")).toBeDefined()
|
|
||||||
expect(spy).toHaveBeenCalled()
|
|
||||||
|
|
||||||
spy.mockRestore()
|
|
||||||
})
|
|
||||||
|
|
||||||
test("new sessions use the replaced provider", async () => {
|
|
||||||
const itemsV1: FeedItem[] = [
|
|
||||||
{
|
|
||||||
id: "v1",
|
|
||||||
sourceId: "test",
|
|
||||||
type: "test",
|
|
||||||
timestamp: new Date(),
|
|
||||||
data: { version: 1 },
|
|
||||||
},
|
|
||||||
]
|
|
||||||
const itemsV2: FeedItem[] = [
|
|
||||||
{
|
|
||||||
id: "v2",
|
|
||||||
sourceId: "test",
|
|
||||||
type: "test",
|
|
||||||
timestamp: new Date(),
|
|
||||||
data: { version: 2 },
|
|
||||||
},
|
|
||||||
]
|
|
||||||
|
|
||||||
const providerV1 = createStubProvider("test", async () => createStubSource("test", itemsV1))
|
|
||||||
const manager = new UserSessionManager({ providers: [providerV1] })
|
|
||||||
|
|
||||||
const providerV2 = createStubProvider("test", async () => createStubSource("test", itemsV2))
|
|
||||||
await manager.replaceProvider(providerV2)
|
|
||||||
|
|
||||||
// New session should use v2
|
|
||||||
const session = await manager.getOrCreate("user-new")
|
|
||||||
const feed = await session.feed()
|
|
||||||
expect(feed.items[0]!.data.version).toBe(2)
|
|
||||||
})
|
|
||||||
|
|
||||||
test("does not affect other providers' sources", async () => {
|
|
||||||
const providerA = createStubProvider("source-a", async () =>
|
|
||||||
createStubSource("source-a", [
|
|
||||||
{
|
|
||||||
id: "a-1",
|
|
||||||
sourceId: "source-a",
|
|
||||||
type: "test",
|
|
||||||
timestamp: new Date(),
|
|
||||||
data: { from: "a" },
|
|
||||||
},
|
|
||||||
]),
|
|
||||||
)
|
|
||||||
const providerB = createStubProvider("source-b", async () =>
|
|
||||||
createStubSource("source-b", [
|
|
||||||
{
|
|
||||||
id: "b-1",
|
|
||||||
sourceId: "source-b",
|
|
||||||
type: "test",
|
|
||||||
timestamp: new Date(),
|
|
||||||
data: { from: "b" },
|
|
||||||
},
|
|
||||||
]),
|
|
||||||
)
|
|
||||||
|
|
||||||
const manager = new UserSessionManager({ providers: [providerA, providerB] })
|
|
||||||
const session = await manager.getOrCreate("user-1")
|
|
||||||
|
|
||||||
// Replace only source-a
|
|
||||||
const providerA2 = createStubProvider("source-a", async () =>
|
|
||||||
createStubSource("source-a", [
|
|
||||||
{
|
|
||||||
id: "a-2",
|
|
||||||
sourceId: "source-a",
|
|
||||||
type: "test",
|
|
||||||
timestamp: new Date(),
|
|
||||||
data: { from: "a-new" },
|
|
||||||
},
|
|
||||||
]),
|
|
||||||
)
|
|
||||||
await manager.replaceProvider(providerA2)
|
|
||||||
|
|
||||||
// source-b should be unaffected
|
|
||||||
expect(session.getSource("source-b")).toBeDefined()
|
|
||||||
const feed = await session.feed()
|
|
||||||
const ids = feed.items.map((i) => i.id).sort()
|
|
||||||
expect(ids).toEqual(["a-2", "b-1"])
|
|
||||||
})
|
|
||||||
|
|
||||||
test("updates sessions that are still being created", async () => {
|
|
||||||
const itemsV1: FeedItem[] = [
|
|
||||||
{
|
|
||||||
id: "v1",
|
|
||||||
sourceId: "test",
|
|
||||||
type: "test",
|
|
||||||
timestamp: new Date(),
|
|
||||||
data: { version: 1 },
|
|
||||||
},
|
|
||||||
]
|
|
||||||
const itemsV2: FeedItem[] = [
|
|
||||||
{
|
|
||||||
id: "v2",
|
|
||||||
sourceId: "test",
|
|
||||||
type: "test",
|
|
||||||
timestamp: new Date(),
|
|
||||||
data: { version: 2 },
|
|
||||||
},
|
|
||||||
]
|
|
||||||
|
|
||||||
let resolveCreation: () => void
|
|
||||||
const creationGate = new Promise<void>((r) => {
|
|
||||||
resolveCreation = r
|
|
||||||
})
|
|
||||||
|
|
||||||
const providerV1 = createStubProvider("test", async () => {
|
|
||||||
await creationGate
|
|
||||||
return createStubSource("test", itemsV1)
|
|
||||||
})
|
|
||||||
const manager = new UserSessionManager({ providers: [providerV1] })
|
|
||||||
|
|
||||||
// Start session creation but don't let it finish yet
|
|
||||||
const sessionPromise = manager.getOrCreate("user-1")
|
|
||||||
|
|
||||||
// Replace provider while session is still pending
|
|
||||||
const providerV2 = createStubProvider("test", async () => createStubSource("test", itemsV2))
|
|
||||||
const replacePromise = manager.replaceProvider(providerV2)
|
|
||||||
|
|
||||||
// Let the original creation finish
|
|
||||||
resolveCreation!()
|
|
||||||
|
|
||||||
const session = await sessionPromise
|
|
||||||
await replacePromise
|
|
||||||
|
|
||||||
// Session should have been updated to v2
|
|
||||||
const feed = await session.feed()
|
|
||||||
expect(feed.items[0]!.data.version).toBe(2)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|||||||
@@ -1,32 +1,26 @@
|
|||||||
import type { FeedSource } from "@aelis/core"
|
import type { FeedSource } from "@aelis/core"
|
||||||
|
|
||||||
import type { FeedEnhancer } from "../enhancement/enhance-feed.ts"
|
import type { FeedEnhancer } from "../enhancement/enhance-feed.ts"
|
||||||
import type { FeedSourceProvider } from "./feed-source-provider.ts"
|
import type { FeedSourceProviderInput } from "./feed-source-provider.ts"
|
||||||
|
|
||||||
import { UserSession } from "./user-session.ts"
|
import { UserSession } from "./user-session.ts"
|
||||||
|
|
||||||
export interface UserSessionManagerConfig {
|
export interface UserSessionManagerConfig {
|
||||||
providers: FeedSourceProvider[]
|
providers: FeedSourceProviderInput[]
|
||||||
feedEnhancer?: FeedEnhancer | null
|
feedEnhancer?: FeedEnhancer | null
|
||||||
}
|
}
|
||||||
|
|
||||||
export class UserSessionManager {
|
export class UserSessionManager {
|
||||||
private sessions = new Map<string, UserSession>()
|
private sessions = new Map<string, UserSession>()
|
||||||
private pending = new Map<string, Promise<UserSession>>()
|
private pending = new Map<string, Promise<UserSession>>()
|
||||||
private readonly providers = new Map<string, FeedSourceProvider>()
|
private readonly providers: FeedSourceProviderInput[]
|
||||||
private readonly feedEnhancer: FeedEnhancer | null
|
private readonly feedEnhancer: FeedEnhancer | null
|
||||||
|
|
||||||
constructor(config: UserSessionManagerConfig) {
|
constructor(config: UserSessionManagerConfig) {
|
||||||
for (const provider of config.providers) {
|
this.providers = config.providers
|
||||||
this.providers.set(provider.sourceId, provider)
|
|
||||||
}
|
|
||||||
this.feedEnhancer = config.feedEnhancer ?? null
|
this.feedEnhancer = config.feedEnhancer ?? null
|
||||||
}
|
}
|
||||||
|
|
||||||
getProvider(sourceId: string): FeedSourceProvider | undefined {
|
|
||||||
return this.providers.get(sourceId)
|
|
||||||
}
|
|
||||||
|
|
||||||
async getOrCreate(userId: string): Promise<UserSession> {
|
async getOrCreate(userId: string): Promise<UserSession> {
|
||||||
const existing = this.sessions.get(userId)
|
const existing = this.sessions.get(userId)
|
||||||
if (existing) return existing
|
if (existing) return existing
|
||||||
@@ -61,45 +55,11 @@ export class UserSessionManager {
|
|||||||
this.pending.delete(userId)
|
this.pending.delete(userId)
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Replaces a provider and updates all active sessions.
|
|
||||||
* The new provider must have the same sourceId as an existing one.
|
|
||||||
* For each active session, re-resolves the source via session.refreshSource.
|
|
||||||
* If the provider fails for a user, the existing source is kept.
|
|
||||||
*/
|
|
||||||
async replaceProvider(provider: FeedSourceProvider): Promise<void> {
|
|
||||||
if (!this.providers.has(provider.sourceId)) {
|
|
||||||
throw new Error(
|
|
||||||
`Cannot replace provider "${provider.sourceId}": no existing provider with that sourceId`,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
this.providers.set(provider.sourceId, provider)
|
|
||||||
|
|
||||||
const updates: Promise<void>[] = []
|
|
||||||
|
|
||||||
for (const [, session] of this.sessions) {
|
|
||||||
updates.push(session.refreshSource(provider))
|
|
||||||
}
|
|
||||||
|
|
||||||
// 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) {
|
|
||||||
updates.push(
|
|
||||||
pendingPromise
|
|
||||||
.then((session) => session.refreshSource(provider))
|
|
||||||
.catch(() => {
|
|
||||||
// Session creation itself failed — nothing to update.
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
await Promise.all(updates)
|
|
||||||
}
|
|
||||||
|
|
||||||
private async createSession(userId: string): Promise<UserSession> {
|
private async createSession(userId: string): Promise<UserSession> {
|
||||||
const results = await Promise.allSettled(
|
const results = await Promise.allSettled(
|
||||||
Array.from(this.providers.values()).map((p) => p.feedSourceForUser(userId)),
|
this.providers.map((p) =>
|
||||||
|
typeof p === "function" ? p(userId) : p.feedSourceForUser(userId),
|
||||||
|
),
|
||||||
)
|
)
|
||||||
|
|
||||||
const sources: FeedSource[] = []
|
const sources: FeedSource[] = []
|
||||||
@@ -121,6 +81,6 @@ export class UserSessionManager {
|
|||||||
console.error("[UserSessionManager] Feed source provider failed:", error)
|
console.error("[UserSessionManager] Feed source provider failed:", error)
|
||||||
}
|
}
|
||||||
|
|
||||||
return new UserSession(userId, sources, this.feedEnhancer)
|
return new UserSession(sources, this.feedEnhancer)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,9 +1,7 @@
|
|||||||
import type { ActionDefinition, ContextEntry, FeedItem, FeedSource } from "@aelis/core"
|
import type { ActionDefinition, ContextEntry, FeedItem, FeedSource } from "@aelis/core"
|
||||||
|
|
||||||
import { LocationSource } from "@aelis/source-location"
|
import { LocationSource } from "@aelis/source-location"
|
||||||
import { describe, expect, spyOn, test } from "bun:test"
|
import { describe, expect, test } from "bun:test"
|
||||||
|
|
||||||
import type { FeedSourceProvider } from "./feed-source-provider.ts"
|
|
||||||
|
|
||||||
import { UserSession } from "./user-session.ts"
|
import { UserSession } from "./user-session.ts"
|
||||||
|
|
||||||
@@ -27,10 +25,7 @@ function createStubSource(id: string, items: FeedItem[] = []): FeedSource {
|
|||||||
|
|
||||||
describe("UserSession", () => {
|
describe("UserSession", () => {
|
||||||
test("registers sources and starts engine", async () => {
|
test("registers sources and starts engine", async () => {
|
||||||
const session = new UserSession("test-user", [
|
const session = new UserSession([createStubSource("test-a"), createStubSource("test-b")])
|
||||||
createStubSource("test-a"),
|
|
||||||
createStubSource("test-b"),
|
|
||||||
])
|
|
||||||
|
|
||||||
const result = await session.engine.refresh()
|
const result = await session.engine.refresh()
|
||||||
|
|
||||||
@@ -39,7 +34,7 @@ describe("UserSession", () => {
|
|||||||
|
|
||||||
test("getSource returns registered source", () => {
|
test("getSource returns registered source", () => {
|
||||||
const location = new LocationSource()
|
const location = new LocationSource()
|
||||||
const session = new UserSession("test-user", [location])
|
const session = new UserSession([location])
|
||||||
|
|
||||||
const result = session.getSource<LocationSource>("aelis.location")
|
const result = session.getSource<LocationSource>("aelis.location")
|
||||||
|
|
||||||
@@ -47,13 +42,13 @@ describe("UserSession", () => {
|
|||||||
})
|
})
|
||||||
|
|
||||||
test("getSource returns undefined for unknown source", () => {
|
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()
|
expect(session.getSource("unknown")).toBeUndefined()
|
||||||
})
|
})
|
||||||
|
|
||||||
test("destroy stops engine and clears sources", () => {
|
test("destroy stops engine and clears sources", () => {
|
||||||
const session = new UserSession("test-user", [createStubSource("test")])
|
const session = new UserSession([createStubSource("test")])
|
||||||
|
|
||||||
session.destroy()
|
session.destroy()
|
||||||
|
|
||||||
@@ -62,7 +57,7 @@ describe("UserSession", () => {
|
|||||||
|
|
||||||
test("engine.executeAction routes to correct source", async () => {
|
test("engine.executeAction routes to correct source", async () => {
|
||||||
const location = new LocationSource()
|
const location = new LocationSource()
|
||||||
const session = new UserSession("test-user", [location])
|
const session = new UserSession([location])
|
||||||
|
|
||||||
await session.engine.executeAction("aelis.location", "update-location", {
|
await session.engine.executeAction("aelis.location", "update-location", {
|
||||||
lat: 51.5,
|
lat: 51.5,
|
||||||
@@ -87,7 +82,7 @@ describe("UserSession.feed", () => {
|
|||||||
data: { value: 42 },
|
data: { value: 42 },
|
||||||
},
|
},
|
||||||
]
|
]
|
||||||
const session = new UserSession("test-user", [createStubSource("test", items)])
|
const session = new UserSession([createStubSource("test", items)])
|
||||||
|
|
||||||
const result = await session.feed()
|
const result = await session.feed()
|
||||||
|
|
||||||
@@ -108,7 +103,7 @@ describe("UserSession.feed", () => {
|
|||||||
const enhancer = async (feedItems: FeedItem[]) =>
|
const enhancer = async (feedItems: FeedItem[]) =>
|
||||||
feedItems.map((item) => ({ ...item, data: { ...item.data, enhanced: true } }))
|
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()
|
const result = await session.feed()
|
||||||
|
|
||||||
@@ -132,7 +127,7 @@ describe("UserSession.feed", () => {
|
|||||||
return feedItems.map((item) => ({ ...item, data: { ...item.data, enhanced: true } }))
|
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()
|
const result1 = await session.feed()
|
||||||
expect(result1.items[0]!.data.enhanced).toBe(true)
|
expect(result1.items[0]!.data.enhanced).toBe(true)
|
||||||
@@ -167,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
|
// First feed triggers refresh + enhancement
|
||||||
const result1 = await session.feed()
|
const result1 = await session.feed()
|
||||||
@@ -210,7 +205,7 @@ describe("UserSession.feed", () => {
|
|||||||
throw new Error("enhancement exploded")
|
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()
|
const result = await session.feed()
|
||||||
|
|
||||||
@@ -219,248 +214,3 @@ describe("UserSession.feed", () => {
|
|||||||
expect(result.items[0]!.data.value).toBe(42)
|
expect(result.items[0]!.data.value).toBe(42)
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
describe("UserSession.replaceSource", () => {
|
|
||||||
test("replaces source and invalidates feed cache", async () => {
|
|
||||||
const itemsA: FeedItem[] = [
|
|
||||||
{
|
|
||||||
id: "a-1",
|
|
||||||
sourceId: "test",
|
|
||||||
type: "test",
|
|
||||||
timestamp: new Date("2025-01-01T00:00:00.000Z"),
|
|
||||||
data: { from: "a" },
|
|
||||||
},
|
|
||||||
]
|
|
||||||
const itemsB: FeedItem[] = [
|
|
||||||
{
|
|
||||||
id: "b-1",
|
|
||||||
sourceId: "test",
|
|
||||||
type: "test",
|
|
||||||
timestamp: new Date("2025-01-01T00:00:00.000Z"),
|
|
||||||
data: { from: "b" },
|
|
||||||
},
|
|
||||||
]
|
|
||||||
|
|
||||||
const sourceA = createStubSource("test", itemsA)
|
|
||||||
const session = new UserSession("test-user", [sourceA])
|
|
||||||
|
|
||||||
const result1 = await session.feed()
|
|
||||||
expect(result1.items).toHaveLength(1)
|
|
||||||
expect(result1.items[0]!.data.from).toBe("a")
|
|
||||||
|
|
||||||
const sourceB = createStubSource("test", itemsB)
|
|
||||||
session.replaceSource("test", sourceB)
|
|
||||||
|
|
||||||
const result2 = await session.feed()
|
|
||||||
expect(result2.items).toHaveLength(1)
|
|
||||||
expect(result2.items[0]!.data.from).toBe("b")
|
|
||||||
})
|
|
||||||
|
|
||||||
test("getSource returns new source after replace", () => {
|
|
||||||
const sourceA = createStubSource("test")
|
|
||||||
const session = new UserSession("test-user", [sourceA])
|
|
||||||
|
|
||||||
const sourceB = createStubSource("test")
|
|
||||||
session.replaceSource("test", sourceB)
|
|
||||||
|
|
||||||
expect(session.getSource("test")).toBe(sourceB)
|
|
||||||
expect(session.getSource("test")).not.toBe(sourceA)
|
|
||||||
})
|
|
||||||
|
|
||||||
test("throws when replacing a source that is not registered", () => {
|
|
||||||
const session = new UserSession("test-user", [createStubSource("test")])
|
|
||||||
|
|
||||||
expect(() => session.replaceSource("nonexistent", createStubSource("other"))).toThrow(
|
|
||||||
'Cannot replace source "nonexistent": not registered',
|
|
||||||
)
|
|
||||||
})
|
|
||||||
|
|
||||||
test("other sources are unaffected by replace", async () => {
|
|
||||||
const sourceA = createStubSource("source-a", [
|
|
||||||
{
|
|
||||||
id: "a-1",
|
|
||||||
sourceId: "source-a",
|
|
||||||
type: "test",
|
|
||||||
timestamp: new Date(),
|
|
||||||
data: { from: "a" },
|
|
||||||
},
|
|
||||||
])
|
|
||||||
const sourceB = createStubSource("source-b", [
|
|
||||||
{
|
|
||||||
id: "b-1",
|
|
||||||
sourceId: "source-b",
|
|
||||||
type: "test",
|
|
||||||
timestamp: new Date(),
|
|
||||||
data: { from: "b" },
|
|
||||||
},
|
|
||||||
])
|
|
||||||
const session = new UserSession("test-user", [sourceA, sourceB])
|
|
||||||
|
|
||||||
const replacement = createStubSource("source-a", [
|
|
||||||
{
|
|
||||||
id: "a-2",
|
|
||||||
sourceId: "source-a",
|
|
||||||
type: "test",
|
|
||||||
timestamp: new Date(),
|
|
||||||
data: { from: "a-new" },
|
|
||||||
},
|
|
||||||
])
|
|
||||||
session.replaceSource("source-a", replacement)
|
|
||||||
|
|
||||||
const result = await session.feed()
|
|
||||||
expect(result.items).toHaveLength(2)
|
|
||||||
|
|
||||||
const ids = result.items.map((i) => i.id).sort()
|
|
||||||
expect(ids).toEqual(["a-2", "b-1"])
|
|
||||||
})
|
|
||||||
|
|
||||||
test("invalidates enhancement cache on replace", async () => {
|
|
||||||
const items: FeedItem[] = [
|
|
||||||
{
|
|
||||||
id: "item-1",
|
|
||||||
sourceId: "test",
|
|
||||||
type: "test",
|
|
||||||
timestamp: new Date(),
|
|
||||||
data: { version: 1 },
|
|
||||||
},
|
|
||||||
]
|
|
||||||
let enhanceCount = 0
|
|
||||||
const enhancer = async (feedItems: FeedItem[]) => {
|
|
||||||
enhanceCount++
|
|
||||||
return feedItems.map((item) => ({ ...item, data: { ...item.data, enhanced: true } }))
|
|
||||||
}
|
|
||||||
|
|
||||||
const session = new UserSession("test-user", [createStubSource("test", items)], enhancer)
|
|
||||||
|
|
||||||
await session.feed()
|
|
||||||
expect(enhanceCount).toBe(1)
|
|
||||||
|
|
||||||
const newItems: FeedItem[] = [
|
|
||||||
{
|
|
||||||
id: "item-2",
|
|
||||||
sourceId: "test",
|
|
||||||
type: "test",
|
|
||||||
timestamp: new Date(),
|
|
||||||
data: { version: 2 },
|
|
||||||
},
|
|
||||||
]
|
|
||||||
session.replaceSource("test", createStubSource("test", newItems))
|
|
||||||
|
|
||||||
const result = await session.feed()
|
|
||||||
expect(enhanceCount).toBe(2)
|
|
||||||
expect(result.items[0]!.id).toBe("item-2")
|
|
||||||
expect(result.items[0]!.data.enhanced).toBe(true)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe("UserSession.removeSource", () => {
|
|
||||||
test("removes source from engine and sources map", () => {
|
|
||||||
const session = new UserSession("test-user", [
|
|
||||||
createStubSource("test-a"),
|
|
||||||
createStubSource("test-b"),
|
|
||||||
])
|
|
||||||
|
|
||||||
session.removeSource("test-a")
|
|
||||||
|
|
||||||
expect(session.getSource("test-a")).toBeUndefined()
|
|
||||||
expect(session.getSource("test-b")).toBeDefined()
|
|
||||||
})
|
|
||||||
|
|
||||||
test("invalidates feed cache on remove", async () => {
|
|
||||||
const items: FeedItem[] = [
|
|
||||||
{
|
|
||||||
id: "item-1",
|
|
||||||
sourceId: "test",
|
|
||||||
type: "test",
|
|
||||||
timestamp: new Date(),
|
|
||||||
data: {},
|
|
||||||
},
|
|
||||||
]
|
|
||||||
const session = new UserSession("test-user", [createStubSource("test", items)])
|
|
||||||
|
|
||||||
const result1 = await session.feed()
|
|
||||||
expect(result1.items).toHaveLength(1)
|
|
||||||
|
|
||||||
session.removeSource("test")
|
|
||||||
|
|
||||||
const result2 = await session.feed()
|
|
||||||
expect(result2.items).toHaveLength(0)
|
|
||||||
})
|
|
||||||
|
|
||||||
test("is a no-op for unknown source", () => {
|
|
||||||
const session = new UserSession("test-user", [createStubSource("test")])
|
|
||||||
|
|
||||||
expect(() => session.removeSource("unknown")).not.toThrow()
|
|
||||||
expect(session.getSource("test")).toBeDefined()
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe("UserSession.refreshSource", () => {
|
|
||||||
test("replaces existing source via provider", async () => {
|
|
||||||
const itemsV1: FeedItem[] = [
|
|
||||||
{
|
|
||||||
id: "v1",
|
|
||||||
sourceId: "test",
|
|
||||||
type: "test",
|
|
||||||
timestamp: new Date(),
|
|
||||||
data: { version: 1 },
|
|
||||||
},
|
|
||||||
]
|
|
||||||
const itemsV2: FeedItem[] = [
|
|
||||||
{
|
|
||||||
id: "v2",
|
|
||||||
sourceId: "test",
|
|
||||||
type: "test",
|
|
||||||
timestamp: new Date(),
|
|
||||||
data: { version: 2 },
|
|
||||||
},
|
|
||||||
]
|
|
||||||
|
|
||||||
const session = new UserSession("test-user", [createStubSource("test", itemsV1)])
|
|
||||||
|
|
||||||
const provider: FeedSourceProvider = {
|
|
||||||
sourceId: "test",
|
|
||||||
async feedSourceForUser() {
|
|
||||||
return createStubSource("test", itemsV2)
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
await session.refreshSource(provider)
|
|
||||||
|
|
||||||
const result = await session.feed()
|
|
||||||
expect(result.items[0]!.data.version).toBe(2)
|
|
||||||
})
|
|
||||||
|
|
||||||
test("throws when source is not registered", async () => {
|
|
||||||
const session = new UserSession("test-user", [createStubSource("existing")])
|
|
||||||
|
|
||||||
const provider: FeedSourceProvider = {
|
|
||||||
sourceId: "new-source",
|
|
||||||
async feedSourceForUser() {
|
|
||||||
return createStubSource("new-source")
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
await expect(session.refreshSource(provider)).rejects.toThrow()
|
|
||||||
})
|
|
||||||
|
|
||||||
test("keeps existing source when provider fails", async () => {
|
|
||||||
const session = new UserSession("test-user", [createStubSource("test")])
|
|
||||||
|
|
||||||
const spy = spyOn(console, "error").mockImplementation(() => {})
|
|
||||||
|
|
||||||
const provider: FeedSourceProvider = {
|
|
||||||
sourceId: "test",
|
|
||||||
async feedSourceForUser() {
|
|
||||||
throw new Error("source disabled")
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
await session.refreshSource(provider)
|
|
||||||
|
|
||||||
expect(session.getSource("test")).toBeDefined()
|
|
||||||
expect(spy).toHaveBeenCalled()
|
|
||||||
|
|
||||||
spy.mockRestore()
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|||||||
@@ -1,10 +1,8 @@
|
|||||||
import { FeedEngine, type FeedItem, type FeedResult, type FeedSource } from "@aelis/core"
|
import { FeedEngine, type FeedItem, type FeedResult, type FeedSource } from "@aelis/core"
|
||||||
|
|
||||||
import type { FeedEnhancer } from "../enhancement/enhance-feed.ts"
|
import type { FeedEnhancer } from "../enhancement/enhance-feed.ts"
|
||||||
import type { FeedSourceProvider } from "./feed-source-provider.ts"
|
|
||||||
|
|
||||||
export class UserSession {
|
export class UserSession {
|
||||||
readonly userId: string
|
|
||||||
readonly engine: FeedEngine
|
readonly engine: FeedEngine
|
||||||
private sources = new Map<string, FeedSource>()
|
private sources = new Map<string, FeedSource>()
|
||||||
private readonly enhancer: FeedEnhancer | null
|
private readonly enhancer: FeedEnhancer | null
|
||||||
@@ -14,8 +12,7 @@ export class UserSession {
|
|||||||
private enhancingPromise: Promise<void> | null = null
|
private enhancingPromise: Promise<void> | null = null
|
||||||
private unsubscribe: (() => void) | null = null
|
private unsubscribe: (() => void) | null = null
|
||||||
|
|
||||||
constructor(userId: string, sources: FeedSource[], enhancer?: FeedEnhancer | null) {
|
constructor(sources: FeedSource[], enhancer?: FeedEnhancer | null) {
|
||||||
this.userId = userId
|
|
||||||
this.engine = new FeedEngine()
|
this.engine = new FeedEngine()
|
||||||
this.enhancer = enhancer ?? null
|
this.enhancer = enhancer ?? null
|
||||||
for (const source of sources) {
|
for (const source of sources) {
|
||||||
@@ -70,80 +67,6 @@ export class UserSession {
|
|||||||
return this.sources.get(sourceId) as T | undefined
|
return this.sources.get(sourceId) as T | undefined
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Re-resolves a source from its provider using this session's userId.
|
|
||||||
* The source must already be registered. Throws if it isn't.
|
|
||||||
* If the provider fails, the existing source is kept.
|
|
||||||
*/
|
|
||||||
async refreshSource(provider: FeedSourceProvider): Promise<void> {
|
|
||||||
if (!this.sources.has(provider.sourceId)) {
|
|
||||||
throw new Error(`Cannot refresh source "${provider.sourceId}": not registered`)
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const newSource = await provider.feedSourceForUser(this.userId)
|
|
||||||
this.replaceSource(provider.sourceId, newSource)
|
|
||||||
} catch (err) {
|
|
||||||
console.error(
|
|
||||||
`[UserSession] refreshSource("${provider.sourceId}") failed for user ${this.userId}:`,
|
|
||||||
err,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Replaces a source in the engine and invalidates all caches.
|
|
||||||
* Stops and restarts the engine to re-establish reactive subscriptions.
|
|
||||||
*/
|
|
||||||
replaceSource(oldSourceId: string, newSource: FeedSource): void {
|
|
||||||
if (!this.sources.has(oldSourceId)) {
|
|
||||||
throw new Error(`Cannot replace source "${oldSourceId}": not registered`)
|
|
||||||
}
|
|
||||||
|
|
||||||
const wasStarted = this.engine.isStarted()
|
|
||||||
|
|
||||||
if (wasStarted) {
|
|
||||||
this.engine.stop()
|
|
||||||
}
|
|
||||||
|
|
||||||
this.engine.unregister(oldSourceId)
|
|
||||||
this.sources.delete(oldSourceId)
|
|
||||||
|
|
||||||
this.engine.register(newSource)
|
|
||||||
this.sources.set(newSource.id, newSource)
|
|
||||||
|
|
||||||
this.invalidateEnhancement()
|
|
||||||
this.enhancingPromise = null
|
|
||||||
|
|
||||||
if (wasStarted) {
|
|
||||||
this.engine.start()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Removes a source from the engine and invalidates all caches.
|
|
||||||
* Stops and restarts the engine to clean up reactive subscriptions.
|
|
||||||
*/
|
|
||||||
removeSource(sourceId: string): void {
|
|
||||||
if (!this.sources.has(sourceId)) return
|
|
||||||
|
|
||||||
const wasStarted = this.engine.isStarted()
|
|
||||||
|
|
||||||
if (wasStarted) {
|
|
||||||
this.engine.stop()
|
|
||||||
}
|
|
||||||
|
|
||||||
this.engine.unregister(sourceId)
|
|
||||||
this.sources.delete(sourceId)
|
|
||||||
|
|
||||||
this.invalidateEnhancement()
|
|
||||||
this.enhancingPromise = null
|
|
||||||
|
|
||||||
if (wasStarted) {
|
|
||||||
this.engine.start()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
destroy(): void {
|
destroy(): void {
|
||||||
this.unsubscribe?.()
|
this.unsubscribe?.()
|
||||||
this.unsubscribe = null
|
this.unsubscribe = null
|
||||||
|
|||||||
@@ -16,7 +16,6 @@ const tflConfig = type({
|
|||||||
})
|
})
|
||||||
|
|
||||||
export class TflSourceProvider implements FeedSourceProvider {
|
export class TflSourceProvider implements FeedSourceProvider {
|
||||||
readonly sourceId = "aelis.tfl"
|
|
||||||
private readonly db: Database
|
private readonly db: Database
|
||||||
private readonly apiKey: string | undefined
|
private readonly apiKey: string | undefined
|
||||||
private readonly client: ITflApi | undefined
|
private readonly client: ITflApi | undefined
|
||||||
|
|||||||
@@ -20,7 +20,6 @@ const weatherConfig = type({
|
|||||||
})
|
})
|
||||||
|
|
||||||
export class WeatherSourceProvider implements FeedSourceProvider {
|
export class WeatherSourceProvider implements FeedSourceProvider {
|
||||||
readonly sourceId = "aelis.weather"
|
|
||||||
private readonly db: Database
|
private readonly db: Database
|
||||||
private readonly credentials: WeatherSourceOptions["credentials"]
|
private readonly credentials: WeatherSourceOptions["credentials"]
|
||||||
private readonly client: WeatherSourceOptions["client"]
|
private readonly client: WeatherSourceOptions["client"]
|
||||||
|
|||||||
@@ -180,31 +180,6 @@ describe("FeedEngine", () => {
|
|||||||
|
|
||||||
expect(engine.refresh()).resolves.toBeDefined()
|
expect(engine.refresh()).resolves.toBeDefined()
|
||||||
})
|
})
|
||||||
|
|
||||||
test("register invalidates feed cache", async () => {
|
|
||||||
const location = createLocationSource()
|
|
||||||
const engine = new FeedEngine().register(location)
|
|
||||||
|
|
||||||
await engine.refresh()
|
|
||||||
expect(engine.lastFeed()).not.toBeNull()
|
|
||||||
|
|
||||||
engine.register(createWeatherSource())
|
|
||||||
|
|
||||||
expect(engine.lastFeed()).toBeNull()
|
|
||||||
})
|
|
||||||
|
|
||||||
test("unregister invalidates feed cache", async () => {
|
|
||||||
const location = createLocationSource()
|
|
||||||
const weather = createWeatherSource()
|
|
||||||
const engine = new FeedEngine().register(location).register(weather)
|
|
||||||
|
|
||||||
await engine.refresh()
|
|
||||||
expect(engine.lastFeed()).not.toBeNull()
|
|
||||||
|
|
||||||
engine.unregister("weather")
|
|
||||||
|
|
||||||
expect(engine.lastFeed()).toBeNull()
|
|
||||||
})
|
|
||||||
})
|
})
|
||||||
|
|
||||||
describe("graph validation", () => {
|
describe("graph validation", () => {
|
||||||
@@ -959,54 +934,4 @@ describe("FeedEngine", () => {
|
|||||||
engine.stop()
|
engine.stop()
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
describe("invalidateCache", () => {
|
|
||||||
test("clears cached result", async () => {
|
|
||||||
const location = createLocationSource()
|
|
||||||
const engine = new FeedEngine().register(location)
|
|
||||||
|
|
||||||
await engine.refresh()
|
|
||||||
expect(engine.lastFeed()).not.toBeNull()
|
|
||||||
|
|
||||||
engine.invalidateCache()
|
|
||||||
|
|
||||||
expect(engine.lastFeed()).toBeNull()
|
|
||||||
})
|
|
||||||
|
|
||||||
test("is safe to call when no cache exists", () => {
|
|
||||||
const engine = new FeedEngine()
|
|
||||||
|
|
||||||
expect(() => engine.invalidateCache()).not.toThrow()
|
|
||||||
expect(engine.lastFeed()).toBeNull()
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
describe("isStarted", () => {
|
|
||||||
test("returns false before start", () => {
|
|
||||||
const engine = new FeedEngine()
|
|
||||||
|
|
||||||
expect(engine.isStarted()).toBe(false)
|
|
||||||
})
|
|
||||||
|
|
||||||
test("returns true after start", () => {
|
|
||||||
const location = createLocationSource()
|
|
||||||
const engine = new FeedEngine().register(location)
|
|
||||||
|
|
||||||
engine.start()
|
|
||||||
|
|
||||||
expect(engine.isStarted()).toBe(true)
|
|
||||||
|
|
||||||
engine.stop()
|
|
||||||
})
|
|
||||||
|
|
||||||
test("returns false after stop", () => {
|
|
||||||
const location = createLocationSource()
|
|
||||||
const engine = new FeedEngine().register(location)
|
|
||||||
|
|
||||||
engine.start()
|
|
||||||
engine.stop()
|
|
||||||
|
|
||||||
expect(engine.isStarted()).toBe(false)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -97,33 +97,23 @@ export class FeedEngine<TItems extends FeedItem = FeedItem> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Registers a FeedSource. Invalidates the cached graph and feed cache.
|
* Registers a FeedSource. Invalidates the cached graph.
|
||||||
*/
|
*/
|
||||||
register<TItem extends FeedItem>(source: FeedSource<TItem>): FeedEngine<TItems | TItem> {
|
register<TItem extends FeedItem>(source: FeedSource<TItem>): FeedEngine<TItems | TItem> {
|
||||||
this.sources.set(source.id, source)
|
this.sources.set(source.id, source)
|
||||||
this.graph = null
|
this.graph = null
|
||||||
this.invalidateCache()
|
|
||||||
return this as FeedEngine<TItems | TItem>
|
return this as FeedEngine<TItems | TItem>
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Unregisters a FeedSource by ID. Invalidates the cached graph and feed cache.
|
* Unregisters a FeedSource by ID. Invalidates the cached graph.
|
||||||
*/
|
*/
|
||||||
unregister(sourceId: string): this {
|
unregister(sourceId: string): this {
|
||||||
this.sources.delete(sourceId)
|
this.sources.delete(sourceId)
|
||||||
this.graph = null
|
this.graph = null
|
||||||
this.invalidateCache()
|
|
||||||
return this
|
return this
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Clears the cached feed result so the next access triggers a fresh refresh.
|
|
||||||
*/
|
|
||||||
invalidateCache(): void {
|
|
||||||
this.cachedResult = null
|
|
||||||
this.cachedAt = null
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Registers a post-processor. Processors run in registration order
|
* Registers a post-processor. Processors run in registration order
|
||||||
* after items are collected, on every update path.
|
* after items are collected, on every update path.
|
||||||
@@ -259,13 +249,6 @@ export class FeedEngine<TItems extends FeedItem = FeedItem> {
|
|||||||
this.cleanups = []
|
this.cleanups = []
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns whether the engine is currently running reactive subscriptions.
|
|
||||||
*/
|
|
||||||
isStarted(): boolean {
|
|
||||||
return this.started
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns the current accumulated context.
|
* Returns the current accumulated context.
|
||||||
*/
|
*/
|
||||||
|
|||||||
Reference in New Issue
Block a user