Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(ai): chat stream indicator (#1640)

Eric Hayes8733fce8a517
diff --git a/js/app/packages/core/component/AI/component/message/AssistantMessage.tsx b/js/app/packages/core/component/AI/component/message/AssistantMessage.tsx
index 246aa8aaa9..76aa16025c 100644
--- a/js/app/packages/core/component/AI/component/message/AssistantMessage.tsx
+++ b/js/app/packages/core/component/AI/component/message/AssistantMessage.tsx
@@ -5,6 +5,7 @@ import { RenderTool } from '@core/component/AI/component/tool/handler';
import { replaceCitations } from '@core/component/LexicalMarkdown/citationsUtils';
import { ENABLE_TTFT } from '@core/constant/featureFlags';
import { createMarkdownFile } from '@core/util/create';
+import { PulsingStar } from '@entity/components/PulsingStar';
import CheckIcon from '@phosphor-icons/core/bold/check-bold.svg?component-solid';
import ClipboardIcon from '@phosphor-icons/core/bold/clipboard-bold.svg?component-solid';
import NotesIcon from '@phosphor-icons/core/bold/file-md-bold.svg?component-solid';
@@ -22,7 +23,6 @@ import {
Show,
Switch,
} from 'solid-js';
-import { LoadingMessage } from './LoadingMessage';
function messageContentIsEmpty(content: ChatMessageContent) {
if (typeof content === 'string' || Array.isArray(content)) {
@@ -203,16 +203,6 @@ export function AssistantMessage(props: {
setIsLoading(false);
});
- // ONLY one model for now so don't show icon
- // const modelIcon = () => {
- // const icon: Component | undefined =
- // MODEL_PROVIDER_ICON[props.message?.model as Model];
- // if (!icon) return MODEL_PROVIDER_ICON[DEFAULT_MODEL];
- // return icon;
- // };
-
- // const citations = () => webCitations()[props.message.id] ?? [];
- // const isCitations = () => citations().length > 0;
return (
<div
class="max-w-full flex flex-col justify-start items-start min-w-0 w-full"
@@ -256,7 +246,7 @@ export function AssistantMessage(props: {
</Match>
</Switch>
<Show when={toolUsageMessageIncomplete()}>
- <LoadingMessage attachments={[]} />
+ <PulsingStar animate kind="streamIndicator" />
</Show>
</div>
<Show when={!props.isStreaming}>
diff --git a/js/app/packages/core/component/AI/component/message/ChatMessages.tsx b/js/app/packages/core/component/AI/component/message/ChatMessages.tsx
index cba6fa78a4..cbbe460e3d 100644
--- a/js/app/packages/core/component/AI/component/message/ChatMessages.tsx
+++ b/js/app/packages/core/component/AI/component/message/ChatMessages.tsx
@@ -1,11 +1,9 @@
-import {
- useChatContext,
- useChatInputContext,
-} from '@core/component/AI/context';
+import { useChatContext } from '@core/component/AI/context';
import type { ChatMessageWithAttachments } from '@core/component/AI/types';
import { asChatMessage } from '@core/component/AI/util/message';
import { StaticMarkdownContext } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';
import { aiChatTheme } from '@core/component/LexicalMarkdown/theme';
+import { PulsingStar } from '@entity/components/PulsingStar';
import type { ChatMessageStream } from '@service-connection/stream';
import { createElementSize } from '@solid-primitives/resize-observer';
import type { Accessor, JSXElement, Setter } from 'solid-js';
@@ -20,12 +18,10 @@ import {
onMount,
Show,
Switch,
- untrack,
} from 'solid-js';
import { createStore } from 'solid-js/store';
import { idStream, timeStream } from '../../util/stream/extendedStream';
import { AssistantMessage } from './AssistantMessage';
-import { LoadingMessage } from './LoadingMessage';
import { UserMessage } from './UserMessage';
export type MessageActions = {};
@@ -57,7 +53,6 @@ function messageContentIsEmpty(message: ChatMessageWithAttachments) {
export function ChatMessages(props: ChatMessagesProps) {
const chat = useChatContext();
- const input = useChatInputContext();
const [messages, setMessages] = [chat.messages, chat.setMessages];
const streamTuple: [
Accessor<ChatMessageStream | undefined>,
@@ -407,16 +402,14 @@ export function ChatMessages(props: ChatMessagesProps) {
scrollToBottom(isNearBottom() ? 'instant' : 'smooth')
}
>
- <LoadingMessage
- attachments={untrack(input.attachments.attached)}
- />
+ <PulsingStar kind="streamIndicator" animate />
</OnMount>
</Show>
{/*
This shows a spinner after a tool call
*/}
<Show when={generatingAfterToolCall()}>
- <LoadingMessage attachments={[]} />
+ <PulsingStar kind="streamIndicator" animate />
</Show>
</div>
</Show>
diff --git a/js/app/packages/core/component/AI/component/message/LoadingMessage.tsx b/js/app/packages/core/component/AI/component/message/LoadingMessage.tsx
deleted file mode 100644
index 4186c2eae6..0000000000
--- a/js/app/packages/core/component/AI/component/message/LoadingMessage.tsx
+++ /dev/null
@@ -1,56 +0,0 @@
-import MacroGridLoader from '@macro-icons/macro-grid-noise-loader-4.svg';
-import type { ChatAttachmentWithName } from '@service-cognition/generated/schemas/chatAttachmentWithName';
-import { createCallback } from '@solid-primitives/rootless';
-import { GlitchText } from '@ui/components/GlitchText';
-import { createEffect, createSignal, untrack } from 'solid-js';
-
-export function LoadingMessage(props: {
- attachments: ChatAttachmentWithName[];
-}) {
- const [currentMessage, setCurrentMessage] = createSignal<number>(0);
-
- const [timeoutHandle, setTimeoutHandle] =
- createSignal<ReturnType<typeof setTimeout>>();
- const messages = createCallback(() => {
- return [
- { text: 'Thinking...', time: 1300 },
- { text: 'Understanding...', time: 1300 },
- ...props.attachments
- .map((a) => {
- if (a.metadata?.type !== 'document') return undefined;
- return {
- text: `Reading through ${a.metadata?.document_name}...`,
- time: 3000,
- };
- })
- .filter((a) => a !== undefined),
- { text: 'Generating Response...', time: 5000 },
- ];
- });
-
- createEffect(() => {
- let currentMessage_ = currentMessage();
- messages();
- let handle = untrack(timeoutHandle);
- if (handle) {
- clearTimeout(handle);
- }
- const newHandle = setTimeout(() => {
- setCurrentMessage((prev) => {
- return (prev + 1) % messages().length;
- });
- }, messages()[currentMessage_].time);
- setTimeoutHandle(newHandle);
- });
-
- return (
- <div class="py-2 font-mono text-sm flex items-center gap-2">
- <MacroGridLoader width={20} height={20} class="text-accent" />
- <GlitchText from={messages()[currentMessage()].text} continuous />
- </div>
- // <p class="h-[32px] flex flex-row items-center justify-start w-full px-2 text-ink-muted animate-pulse text-sm">
-
- // {messages()[currentMessage()].text}
- // </p>
- );
-}
diff --git a/js/app/packages/entity/src/components/PulsingStar.tsx b/js/app/packages/entity/src/components/PulsingStar.tsx
new file mode 100644
index 0000000000..cf7a8e0599
--- /dev/null
+++ b/js/app/packages/entity/src/components/PulsingStar.tsx
@@ -0,0 +1,34 @@
+import { AnimatedStarIcon } from '@macro-icons/wide/animating/star';
+import type { StreamEvent } from '@service-connection/generated/schemas';
+import { createSignal, onCleanup } from 'solid-js';
+
+export type StreamIndicatorProps = {
+ streamState?: StreamEvent;
+};
+
+const kind = {
+ listIcon: 'size-4 text-chat',
+ streamIndicator: 'size-4 text-accent',
+} as const;
+
+type Kind = keyof typeof kind;
+
+export function PulsingStar(props: { kind: Kind; animate?: boolean }) {
+ const [pulse, setPulse] = createSignal(false);
+
+ const interval = setInterval(() => {
+ if (props.animate) {
+ setPulse((p) => !p);
+ } else {
+ setPulse(false);
+ }
+ }, 900);
+
+ onCleanup(() => clearInterval(interval));
+
+ return (
+ <div class={kind[props.kind]}>
+ <AnimatedStarIcon triggerAnimation={pulse()} />
+ </div>
+ );
+}
diff --git a/js/app/packages/entity/src/composed/ListEntity.tsx b/js/app/packages/entity/src/composed/ListEntity.tsx
index 35891cde88..cf75578ba5 100644
--- a/js/app/packages/entity/src/composed/ListEntity.tsx
+++ b/js/app/packages/entity/src/composed/ListEntity.tsx
@@ -1,6 +1,7 @@
import type { DateValue } from '@core/util/date';
import { visibleLength, windowSearchMatch } from '@core/util/searchHighlight';
import { Entity } from '../entity';
+import type { StreamEvent } from '@service-connection/generated/schemas';
import {
isChannelEntity,
isEmailEntity,
@@ -12,6 +13,10 @@ import {
isTaskEntity,
} from '../types/entity';
import { Match, Show, Switch, type Ref } from 'solid-js';
+import {
+ getStreamState,
+ subscribeToStreamState,
+} from '@service-connection/stream-events';
import {
isWithNotification,
type WithNotification,
@@ -87,6 +92,7 @@ interface LayoutProps {
isShared: boolean;
hasNotifications: boolean;
showContentHits: boolean;
+ streamState?: StreamEvent;
onProjectClick?: (
entity: ProjectEntity,
e: PointerEvent | MouseEvent
@@ -190,7 +196,7 @@ function NarrowLayout(props: LayoutProps) {
<UnreadIndicator active />
</Show>
<div class="size-4 shrink-0">
- <Entity.Icon entity={props.entity} />
+ <Entity.Icon entity={props.entity} streamState={props.streamState} />
</div>
<Switch>
<Match when={isEmailEntity(props.entity) && props.entity}>
@@ -294,7 +300,7 @@ function WideLayout(props: LayoutProps) {
class="font-semibold truncate items-center gap-2 flex"
>
<div class="size-4 shrink-0">
- <Entity.Icon entity={props.entity} />
+ <Entity.Icon entity={props.entity} streamState={props.streamState} />
</div>
<Switch>
<Match when={isEmailEntity(props.entity) && props.entity}>
@@ -368,6 +374,9 @@ export function ListEntity(props: ListEntityProps) {
const unread = () => unreadFilterFn(props.entity);
const isShared = useIsShared(props.entity);
+ subscribeToStreamState(props.entity.id, props.entity.type);
+ const streamState = getStreamState(props.entity.id);
+
const hasNotifications = () => {
if (!props.showUnrollNotifications) return false;
if (!isWithNotification(props.entity)) return false;
@@ -389,6 +398,7 @@ export function ListEntity(props: ListEntityProps) {
isShared: isShared(),
hasNotifications: hasNotifications(),
showContentHits: showContentHits(),
+ streamState: streamState(),
onProjectClick: props.onProjectClick,
});
diff --git a/js/app/packages/entity/src/extractors/entity-icon.tsx b/js/app/packages/entity/src/extractors/entity-icon.tsx
index e88fc1b0e2..464894cb5c 100644
--- a/js/app/packages/entity/src/extractors/entity-icon.tsx
+++ b/js/app/packages/entity/src/extractors/entity-icon.tsx
@@ -5,13 +5,16 @@ import {
} from '@core/component/EntityIcon';
import { UserIcon } from '@core/component/UserIcon';
import { useUserId } from '@core/context/user';
-import { Show } from 'solid-js';
+import type { StreamEvent } from '@service-connection/generated/schemas';
+import { Match, Show, Switch } from 'solid-js';
+import { match } from 'ts-pattern';
+import { PulsingStar } from '../components/PulsingStar';
import type { ChannelEntity, EntityData } from '../types/entity';
import { isChannelEntity, isTaskEntity } from '../types/entity';
-import { match } from 'ts-pattern';
interface EntityIconProps {
entity: EntityData;
+ streamState?: StreamEvent;
}
function DirectMessageIcon(props: { entity: ChannelEntity }) {
@@ -55,12 +58,21 @@ export function EntityIcon(props: EntityIconProps) {
const isDirectMessage = () => iconType() === 'direct_message';
+ const isChatEntity = () => props.entity.type === 'chat';
+
return (
- <Show
- when={isDirectMessage()}
+ <Switch
fallback={<CoreEntityIcon targetType={validIconType()} size="fill" />}
>
- <DirectMessageIcon entity={props.entity as ChannelEntity} />
- </Show>
+ <Match when={isDirectMessage()}>
+ <DirectMessageIcon entity={props.entity as ChannelEntity} />
+ </Match>
+ <Match when={isChatEntity()}>
+ <PulsingStar
+ kind="listIcon"
+ animate={props.streamState?.type === 'created'}
+ />
+ </Match>
+ </Switch>
);
}
diff --git a/js/app/packages/service-clients/service-connection/generated/schemas/index.ts b/js/app/packages/service-clients/service-connection/generated/schemas/index.ts
index 8fad3cb08a..52c0755e30 100644
--- a/js/app/packages/service-clients/service-connection/generated/schemas/index.ts
+++ b/js/app/packages/service-clients/service-connection/generated/schemas/index.ts
@@ -14,11 +14,24 @@ export * from './sendMessageBody';
export * from './sendMessageResponse';
export * from './storedConnectionEntity';
export * from './storedConnectionEntityLastPing';
+export * from './streamEvent';
+export * from './streamEventOneOf';
+export * from './streamEventOneOfAllOf';
+export * from './streamEventOneOfAllOfType';
+export * from './streamEventOneOfFour';
+export * from './streamEventOneOfFourAllOf';
+export * from './streamEventOneOfFourAllOfType';
+export * from './streamEvents';
+export * from './streamId';
+export * from './streamItem';
export * from './stringIDResponse';
export * from './toWebsocketMessage';
export * from './toWebsocketMessageOneOf';
export * from './toWebsocketMessageOneOfAllOf';
export * from './toWebsocketMessageOneOfAllOfType';
+export * from './toWebsocketMessageOneOfFour';
+export * from './toWebsocketMessageOneOfFourAllOf';
+export * from './toWebsocketMessageOneOfFourAllOfType';
export * from './trackAction';
export * from './trackEntityMessage';
export * from './trackEntityMessageAllOf';
diff --git a/js/app/packages/service-clients/service-connection/generated/schemas/streamEvent.ts b/js/app/packages/service-clients/service-connection/generated/schemas/streamEvent.ts
new file mode 100644
index 0000000000..5dfaa72022
--- /dev/null
+++ b/js/app/packages/service-clients/service-connection/generated/schemas/streamEvent.ts
@@ -0,0 +1,13 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * connection_gateway
+ * OpenAPI spec version: 0.1.0
+ */
+import type { StreamEventOneOf } from './streamEventOneOf';
+import type { StreamEventOneOfFour } from './streamEventOneOfFour';
+
+/**
+ * Events published through the notification channel.
+ */
+export type StreamEvent = StreamEventOneOf | StreamEventOneOfFour;
diff --git a/js/app/packages/service-clients/service-connection/generated/schemas/streamEventOneOf.ts b/js/app/packages/service-clients/service-connection/generated/schemas/streamEventOneOf.ts
new file mode 100644
index 0000000000..0d417464fc
--- /dev/null
+++ b/js/app/packages/service-clients/service-connection/generated/schemas/streamEventOneOf.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * connection_gateway
+ * OpenAPI spec version: 0.1.0
+ */
+
+import type { StreamEventOneOfAllOf } from './streamEventOneOfAllOf';
+import type { StreamId } from './streamId';
+
+/**
+ * A new stream was created.
+ */
+export type StreamEventOneOf = StreamId & StreamEventOneOfAllOf;
diff --git a/js/app/packages/service-clients/service-connection/generated/schemas/streamEventOneOfAllOf.ts b/js/app/packages/service-clients/service-connection/generated/schemas/streamEventOneOfAllOf.ts
new file mode 100644
index 0000000000..4ce1b88d5c
--- /dev/null
+++ b/js/app/packages/service-clients/service-connection/generated/schemas/streamEventOneOfAllOf.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * connection_gateway
+ * OpenAPI spec version: 0.1.0
+ */
+import type { StreamEventOneOfAllOfType } from './streamEventOneOfAllOfType';
+
+export type StreamEventOneOfAllOf = {
+ type: StreamEventOneOfAllOfType;
+};
diff --git a/js/app/packages/service-clients/service-connection/generated/schemas/streamEventOneOfAllOfType.ts b/js/app/packages/service-clients/service-connection/generated/schemas/streamEventOneOfAllOfType.ts
new file mode 100644
index 0000000000..743cc77c4f
--- /dev/null
+++ b/js/app/packages/service-clients/service-connection/generated/schemas/streamEventOneOfAllOfType.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * connection_gateway
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type StreamEventOneOfAllOfType =
+ (typeof StreamEventOneOfAllOfType)[keyof typeof StreamEventOneOfAllOfType];
+
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+export const StreamEventOneOfAllOfType = {
+ created: 'created',
+} as const;
diff --git a/js/app/packages/service-clients/service-connection/generated/schemas/streamEventOneOfFour.ts b/js/app/packages/service-clients/service-connection/generated/schemas/streamEventOneOfFour.ts
new file mode 100644
index 0000000000..7bc1799c6c
--- /dev/null
+++ b/js/app/packages/service-clients/service-connection/generated/schemas/streamEventOneOfFour.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * connection_gateway
+ * OpenAPI spec version: 0.1.0
+ */
+
+import type { StreamEventOneOfFourAllOf } from './streamEventOneOfFourAllOf';
+import type { StreamId } from './streamId';
+
+/**
+ * A stream was closed.
+ */
+export type StreamEventOneOfFour = StreamId & StreamEventOneOfFourAllOf;
diff --git a/js/app/packages/service-clients/service-connection/generated/schemas/streamEventOneOfFourAllOf.ts b/js/app/packages/service-clients/service-connection/generated/schemas/streamEventOneOfFourAllOf.ts
new file mode 100644
index 0000000000..446c205d14
--- /dev/null
+++ b/js/app/packages/service-clients/service-connection/generated/schemas/streamEventOneOfFourAllOf.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * connection_gateway
+ * OpenAPI spec version: 0.1.0
+ */
+import type { StreamEventOneOfFourAllOfType } from './streamEventOneOfFourAllOfType';
+
+export type StreamEventOneOfFourAllOf = {
+ type: StreamEventOneOfFourAllOfType;
+};
diff --git a/js/app/packages/service-clients/service-connection/generated/schemas/streamEventOneOfFourAllOfType.ts b/js/app/packages/service-clients/service-connection/generated/schemas/streamEventOneOfFourAllOfType.ts
new file mode 100644
index 0000000000..c827fce7a8
--- /dev/null
+++ b/js/app/packages/service-clients/service-connection/generated/schemas/streamEventOneOfFourAllOfType.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * connection_gateway
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type StreamEventOneOfFourAllOfType =
+ (typeof StreamEventOneOfFourAllOfType)[keyof typeof StreamEventOneOfFourAllOfType];
+
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+export const StreamEventOneOfFourAllOfType = {
+ closed: 'closed',
+} as const;
diff --git a/js/app/packages/service-clients/service-connection/generated/schemas/streamEvents.ts b/js/app/packages/service-clients/service-connection/generated/schemas/streamEvents.ts
new file mode 100644
index 0000000000..ea3e3a17c1
--- /dev/null
+++ b/js/app/packages/service-clients/service-connection/generated/schemas/streamEvents.ts
@@ -0,0 +1,12 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * connection_gateway
+ * OpenAPI spec version: 0.1.0
+ */
+import type { Entity } from './entity';
+
+/**
+ * subscribe to stream events from entity
+ */
+export type StreamEvents = Entity;
diff --git a/js/app/packages/service-clients/service-connection/generated/schemas/streamId.ts b/js/app/packages/service-clients/service-connection/generated/schemas/streamId.ts
new file mode 100644
index 0000000000..b9f1f880cf
--- /dev/null
+++ b/js/app/packages/service-clients/service-connection/generated/schemas/streamId.ts
@@ -0,0 +1,13 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * connection_gateway
+ * OpenAPI spec version: 0.1.0
+ */
+import type { EntityType } from './entityType';
+
+export interface StreamId {
+ entity_id: string;
+ entity_type: EntityType;
+ stream_id: string;
+}
diff --git a/js/app/packages/service-clients/service-connection/generated/schemas/streamItem.ts b/js/app/packages/service-clients/service-connection/generated/schemas/streamItem.ts
new file mode 100644
index 0000000000..e8cc5a6efc
--- /dev/null
+++ b/js/app/packages/service-clients/service-connection/generated/schemas/streamItem.ts
@@ -0,0 +1,12 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * connection_gateway
+ * OpenAPI spec version: 0.1.0
+ */
+import type { StreamId } from './streamId';
+
+export interface StreamItem {
+ id: StreamId;
+ payload: unknown;
+}
diff --git a/js/app/packages/service-clients/service-connection/generated/schemas/toWebsocketMessage.ts b/js/app/packages/service-clients/service-connection/generated/schemas/toWebsocketMessage.ts
index 281a8012bb..cf29313166 100644
--- a/js/app/packages/service-clients/service-connection/generated/schemas/toWebsocketMessage.ts
+++ b/js/app/packages/service-clients/service-connection/generated/schemas/toWebsocketMessage.ts
@@ -5,5 +5,8 @@
* OpenAPI spec version: 0.1.0
*/
import type { ToWebsocketMessageOneOf } from './toWebsocketMessageOneOf';
+import type { ToWebsocketMessageOneOfFour } from './toWebsocketMessageOneOfFour';
-export type ToWebsocketMessage = ToWebsocketMessageOneOf;
+export type ToWebsocketMessage =
+ | ToWebsocketMessageOneOf
+ | ToWebsocketMessageOneOfFour;
diff --git a/js/app/packages/service-clients/service-connection/generated/schemas/toWebsocketMessageOneOfFour.ts b/js/app/packages/service-clients/service-connection/generated/schemas/toWebsocketMessageOneOfFour.ts
new file mode 100644
index 0000000000..ce8abdd17b
--- /dev/null
+++ b/js/app/packages/service-clients/service-connection/generated/schemas/toWebsocketMessageOneOfFour.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * connection_gateway
+ * OpenAPI spec version: 0.1.0
+ */
+import type { StreamEvents } from './streamEvents';
+import type { ToWebsocketMessageOneOfFourAllOf } from './toWebsocketMessageOneOfFourAllOf';
+
+export type ToWebsocketMessageOneOfFour = StreamEvents &
+ ToWebsocketMessageOneOfFourAllOf;
diff --git a/js/app/packages/service-clients/service-connection/generated/schemas/toWebsocketMessageOneOfFourAllOf.ts b/js/app/packages/service-clients/service-connection/generated/schemas/toWebsocketMessageOneOfFourAllOf.ts
new file mode 100644
index 0000000000..9f24aad1bf
--- /dev/null
+++ b/js/app/packages/service-clients/service-connection/generated/schemas/toWebsocketMessageOneOfFourAllOf.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * connection_gateway
+ * OpenAPI spec version: 0.1.0
+ */
+import type { ToWebsocketMessageOneOfFourAllOfType } from './toWebsocketMessageOneOfFourAllOfType';
+
+export type ToWebsocketMessageOneOfFourAllOf = {
+ type: ToWebsocketMessageOneOfFourAllOfType;
+};
diff --git a/js/app/packages/service-clients/service-connection/generated/schemas/toWebsocketMessageOneOfFourAllOfType.ts b/js/app/packages/service-clients/service-connection/generated/schemas/toWebsocketMessageOneOfFourAllOfType.ts
new file mode 100644
index 0000000000..b1bed75fb7
--- /dev/null
+++ b/js/app/packages/service-clients/service-connection/generated/schemas/toWebsocketMessageOneOfFourAllOfType.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * connection_gateway
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type ToWebsocketMessageOneOfFourAllOfType =
+ (typeof ToWebsocketMessageOneOfFourAllOfType)[keyof typeof ToWebsocketMessageOneOfFourAllOfType];
+
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+export const ToWebsocketMessageOneOfFourAllOfType = {
+ stream_events: 'stream_events',
+} as const;
diff --git a/js/app/packages/service-clients/service-connection/openapi.json b/js/app/packages/service-clients/service-connection/openapi.json
index 5cd9fd938c..3a855b6c13 100644
--- a/js/app/packages/service-clients/service-connection/openapi.json
+++ b/js/app/packages/service-clients/service-connection/openapi.json
@@ -343,6 +343,82 @@
}
}
},
+ "StreamEvent": {
+ "oneOf": [
+ {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/StreamId",
+ "description": "A new stream was created."
+ },
+ {
+ "type": "object",
+ "required": ["type"],
+ "properties": {
+ "type": {
+ "type": "string",
+ "enum": ["created"]
+ }
+ }
+ }
+ ],
+ "description": "A new stream was created."
+ },
+ {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/StreamId",
+ "description": "A stream was closed."
+ },
+ {
+ "type": "object",
+ "required": ["type"],
+ "properties": {
+ "type": {
+ "type": "string",
+ "enum": ["closed"]
+ }
+ }
+ }
+ ],
+ "description": "A stream was closed."
+ }
+ ],
+ "description": "Events published through the notification channel."
+ },
+ "StreamEvents": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/Entity"
+ }
+ ],
+ "description": "subscribe to stream events from entity"
+ },
+ "StreamId": {
+ "type": "object",
+ "required": ["entity_type", "entity_id", "stream_id"],
+ "properties": {
+ "entity_id": {
+ "type": "string"
+ },
+ "entity_type": {
+ "$ref": "#/components/schemas/EntityType"
+ },
+ "stream_id": {
+ "type": "string"
+ }
+ }
+ },
+ "StreamItem": {
+ "type": "object",
+ "required": ["id", "payload"],
+ "properties": {
+ "id": {
+ "$ref": "#/components/schemas/StreamId"
+ },
+ "payload": {}
+ }
+ },
"StringIDResponse": {
"type": "object",
"required": ["id"],
@@ -370,6 +446,23 @@
}
}
]
+ },
+ {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/StreamEvents"
+ },
+ {
+ "type": "object",
+ "required": ["type"],
+ "properties": {
+ "type": {
+ "type": "string",
+ "enum": ["stream_events"]
+ }
+ }
+ }
+ ]
}
]
},
diff --git a/js/app/packages/service-clients/service-connection/stream-events.ts b/js/app/packages/service-clients/service-connection/stream-events.ts
new file mode 100644
index 0000000000..ff5d88cd56
--- /dev/null
+++ b/js/app/packages/service-clients/service-connection/stream-events.ts
@@ -0,0 +1,39 @@
+import type { Accessor } from 'solid-js';
+import { createStore } from 'solid-js/store';
+import type { EntityType, StreamEvent } from './generated/schemas';
+import { isStreamEntity } from './stream';
+import { createConnectionWebsocketEffect, ws } from './websocket';
+
+const [streamState, setStreamState] = createStore<Record<string, StreamEvent>>(
+ {}
+);
+const subscribed = new Set<string>();
+
+createConnectionWebsocketEffect((data) => {
+ if (data.type !== 'stream_event') return;
+ try {
+ const event = JSON.parse(data.data) as StreamEvent;
+ setStreamState(event.entity_id, event);
+ } catch {
+ return;
+ }
+});
+
+export function getStreamState(
+ entity_id: string
+): Accessor<StreamEvent | undefined> {
+ return () => streamState[entity_id];
+}
+
+export function subscribeToStreamState(
+ entity_id: string,
+ entity_type: EntityType
+) {
+ if (!isStreamEntity(entity_type) || subscribed.has(entity_id)) return;
+ subscribed.add(entity_id);
+ ws.send({
+ type: 'stream_events',
+ entity_id,
+ entity_type: entity_type,
+ });
+}
diff --git a/js/app/packages/service-clients/service-connection/stream.ts b/js/app/packages/service-clients/service-connection/stream.ts
index 54ed93fe6f..845972e85a 100644
--- a/js/app/packages/service-clients/service-connection/stream.ts
+++ b/js/app/packages/service-clients/service-connection/stream.ts
@@ -3,12 +3,19 @@ import type { Accessor, Setter } from 'solid-js';
import { createSignal } from 'solid-js';
import { createStore, produce } from 'solid-js/store';
import { match } from 'ts-pattern';
+import type { EntityType } from './generated/schemas';
import { createConnectionWebsocketEffect } from './websocket';
// entities that support streaming
export type StreamType = {
chat: ChatStream;
};
+export function isStreamEntity(
+ entity_type: EntityType
+): entity_type is keyof StreamType {
+ return entity_type === 'chat';
+}
+
export type StreamId = {
entity_type: keyof StreamType;
entity_id: string;
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index e568c8af52..e6bf28e7a0 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -9163,6 +9163,7 @@ dependencies = [
"tokio",
"tokio-test",
"tracing",
+ "utoipa",
]
[[package]]
diff --git a/rust/cloud-storage/connection_gateway/src/api/connection/messages.rs b/rust/cloud-storage/connection_gateway/src/api/connection/messages.rs
index f0763df8d2..47b886d2d8 100644
--- a/rust/cloud-storage/connection_gateway/src/api/connection/messages.rs
+++ b/rust/cloud-storage/connection_gateway/src/api/connection/messages.rs
@@ -5,7 +5,7 @@ use crate::{
tracking::{EntityConnectionExt, TrackingData},
websocket::ToWebsocketMessage,
},
- service::tracker,
+ service::{stream_event::handle_stream_events, tracker},
};
use anyhow::{Context, Result};
use axum::extract::ws::{Message, WebSocket};
@@ -106,6 +106,9 @@ pub async fn handle_message(
.await
.ok();
}
+ ToWebsocketMessage::StreamEvents(message) => {
+ handle_stream_events(connection_context, sender.clone(), message)
+ }
};
Ok(())
diff --git a/rust/cloud-storage/connection_gateway/src/api/swagger.rs b/rust/cloud-storage/connection_gateway/src/api/swagger.rs
index 81a9a2de29..623c9e79b7 100644
--- a/rust/cloud-storage/connection_gateway/src/api/swagger.rs
+++ b/rust/cloud-storage/connection_gateway/src/api/swagger.rs
@@ -8,6 +8,7 @@ use crate::model::websocket::{ToWebsocketMessage, TrackEntityMessage};
use model::response::{GenericErrorResponse, StringIDResponse};
use model_entity::{Entity, EntityType};
use models_bulk_upload::UploadFolderStatusUpdate;
+use stream::domain::{StreamEvent, StreamItem};
use utoipa::OpenApi;
#[derive(OpenApi)]
@@ -36,7 +37,10 @@ use utoipa::OpenApi;
StoredConnectionEntity,
EntityType,
- UploadFolderStatusUpdate
+ UploadFolderStatusUpdate,
+
+ StreamEvent,
+ StreamItem,
),
),
tags(
diff --git a/rust/cloud-storage/connection_gateway/src/model/message.rs b/rust/cloud-storage/connection_gateway/src/model/message.rs
index f11e260867..9270076b88 100644
--- a/rust/cloud-storage/connection_gateway/src/model/message.rs
+++ b/rust/cloud-storage/connection_gateway/src/model/message.rs
@@ -1,6 +1,7 @@
use anyhow::Result;
use model_entity::Entity;
use serde::{Deserialize, Serialize};
+use stream::domain::StreamEvent;
use utoipa::ToSchema;
#[derive(Serialize, Deserialize, Clone, Debug)]
@@ -10,6 +11,19 @@ pub struct Message {
pub data: String,
}
+static STREAM_EVENT_TYPE: &str = "stream_event";
+impl TryFrom<StreamEvent> for Message {
+ type Error = anyhow::Error;
+ fn try_from(value: StreamEvent) -> Result<Self, Self::Error> {
+ serde_json::to_string(&value)
+ .map(|data| Self {
+ data,
+ message_type: STREAM_EVENT_TYPE.into(),
+ })
+ .map_err(anyhow::Error::from)
+ }
+}
+
#[derive(Serialize, Deserialize, Clone, Debug)]
pub enum OutgoingMessage {
Pong,
diff --git a/rust/cloud-storage/connection_gateway/src/model/websocket.rs b/rust/cloud-storage/connection_gateway/src/model/websocket.rs
index 7aa3d573e4..afbf95948a 100644
--- a/rust/cloud-storage/connection_gateway/src/model/websocket.rs
+++ b/rust/cloud-storage/connection_gateway/src/model/websocket.rs
@@ -12,9 +12,18 @@ pub struct TrackEntityMessage {
pub action: TrackAction,
}
+/// subscribe to stream events from entity
+#[derive(serde::Serialize, serde::Deserialize, Debug, ToSchema)]
+pub struct StreamEvents {
+ #[serde(flatten)]
+ pub entity: Entity<'static>,
+}
+
#[derive(serde::Serialize, serde::Deserialize, Debug, ToSchema)]
#[serde(rename_all = "snake_case", tag = "type")]
pub enum ToWebsocketMessage {
#[serde(rename = "track_entity")]
TrackEntityMessage(TrackEntityMessage),
+ #[serde(rename = "stream_events")]
+ StreamEvents(StreamEvents),
}
diff --git a/rust/cloud-storage/connection_gateway/src/service/mod.rs b/rust/cloud-storage/connection_gateway/src/service/mod.rs
index d11164baf0..4724ee0abb 100644
--- a/rust/cloud-storage/connection_gateway/src/service/mod.rs
+++ b/rust/cloud-storage/connection_gateway/src/service/mod.rs
@@ -2,4 +2,5 @@ pub mod connection;
pub mod dynamodb;
pub mod redis;
pub mod sender;
+pub mod stream_event;
pub mod tracker;
diff --git a/rust/cloud-storage/connection_gateway/src/service/stream_event.rs b/rust/cloud-storage/connection_gateway/src/service/stream_event.rs
new file mode 100644
index 0000000000..803e2692d0
--- /dev/null
+++ b/rust/cloud-storage/connection_gateway/src/service/stream_event.rs
@@ -0,0 +1,72 @@
+//! Handle sending StreamEvent to a user
+//! Note: StreamEvents are not the same as StreamItems.
+//! StreamEvents are notifcations about the state of a stream
+//! while StreamItems represent stream data itself
+
+use stream::domain::{StreamEvent, StreamId};
+use tokio::sync::mpsc::Sender;
+
+use crate::model::{
+ connection::ConnectionContext, message::OutgoingMessage, websocket::StreamEvents,
+};
+
+#[tracing::instrument(skip(context, sender))]
+pub fn handle_stream_events(
+ context: ConnectionContext<'_>,
+ sender: Sender<OutgoingMessage>,
+ incoming_message: StreamEvents,
+) {
+ let repo = context.api_context.stream_manager.repo();
+
+ tokio::spawn(async move {
+ // if any prexisting streams exist emit open entity
+ if let Ok(streams) = repo
+ .active_streams(&incoming_message.entity.entity_id)
+ .await
+ && !streams.is_empty()
+ {
+ let stream_event = StreamEvent::Created(StreamId {
+ entity_id: incoming_message.entity.entity_id.clone().into(),
+ entity_type: incoming_message.entity.entity_type,
+ stream_id: streams[0].stream_id.clone(),
+ });
+
+ if let Ok(message) = stream_event.try_into()
+ && sender
+ .send(OutgoingMessage::Message(message))
+ .await
+ .is_err()
+ {
+ return;
+ }
+ }
+ let mut connection_heartbeat = tokio::time::interval(std::time::Duration::from_secs(60));
+ let mut rx = repo.notify().await;
+ loop {
+ tokio::select! {
+ result = rx.recv() => {
+ let Ok(event) = result else {
+ tracing::warn!("notifier exited");
+ break
+ };
+ if event.id().entity_id != incoming_message.entity.entity_id {
+ continue;
+ }
+ let Ok(message) = event.try_into().inspect_err(|e| {
+ tracing::error!(error=?e, "failed to serialize stream event message");
+ }) else {
+ continue;
+ };
+ if sender.send(OutgoingMessage::Message(message)).await.is_err() {
+ break;
+ };
+ }
+ _ = connection_heartbeat.tick() => {
+ if sender.send(OutgoingMessage::Pong).await.is_err() {
+ break;
+ }
+ }
+ }
+ }
+ });
+}
diff --git a/rust/cloud-storage/document_cognition_service/src/api/context.rs b/rust/cloud-storage/document_cognition_service/src/api/context.rs
index 035bbcfff6..e0bd4350f0 100644
--- a/rust/cloud-storage/document_cognition_service/src/api/context.rs
+++ b/rust/cloud-storage/document_cognition_service/src/api/context.rs
@@ -38,12 +38,12 @@ pub static GLOBAL_CONTEXT: OnceLock<ApiContext> = OnceLock::new();
#[cfg(test)]
mod mock_stream {
use std::sync::Arc;
- use stream::domain::{ItemId, ItemStream, Result, StreamId, StreamRepo};
+ use stream::domain::{ItemId, ItemStream, Result, StreamEvent, StreamId, StreamRepo};
use tokio::sync::broadcast::{self, Receiver};
/// Mock StreamRepo for testing - does nothing but satisfies the interface
pub struct MockStreamRepo {
- tx: broadcast::Sender<StreamId>,
+ tx: broadcast::Sender<StreamEvent>,
}
impl MockStreamRepo {
@@ -71,7 +71,7 @@ mod mock_stream {
Ok(vec![])
}
- async fn notify(&self) -> Receiver<StreamId> {
+ async fn notify(&self) -> Receiver<StreamEvent> {
self.tx.subscribe()
}
}
diff --git a/rust/cloud-storage/document_cognition_service/src/api/stream/chat_message.rs b/rust/cloud-storage/document_cognition_service/src/api/stream/chat_message.rs
index 3135ba0e68..d0badf0255 100644
--- a/rust/cloud-storage/document_cognition_service/src/api/stream/chat_message.rs
+++ b/rust/cloud-storage/document_cognition_service/src/api/stream/chat_message.rs
@@ -516,6 +516,5 @@ fn stream_and_save_message(
durable_stream_id,
Box::pin(payload_stream),
None,
- None,
);
}
diff --git a/rust/cloud-storage/stream/Cargo.toml b/rust/cloud-storage/stream/Cargo.toml
index 2ce4e7ad97..70f1cb6f67 100644
--- a/rust/cloud-storage/stream/Cargo.toml
+++ b/rust/cloud-storage/stream/Cargo.toml
@@ -8,6 +8,7 @@ publish=false
redis-test=[]
[dependencies]
+utoipa = { workspace = true }
serde = { version = "1.0", features = ["derive"] }
serde_json = { workspace = true }
tokio = { version = "1", features = ["sync", "rt", "macros", "time"] }
diff --git a/rust/cloud-storage/stream/src/domain/ext.rs b/rust/cloud-storage/stream/src/domain/ext.rs
index f617568caf..a1948f322f 100644
--- a/rust/cloud-storage/stream/src/domain/ext.rs
+++ b/rust/cloud-storage/stream/src/domain/ext.rs
@@ -6,8 +6,6 @@ use futures::StreamExt;
use std::sync::Arc;
use std::time::Duration;
-const DEFAULT_CLOSE_DELAY: std::time::Duration = std::time::Duration::from_secs(60);
-
pub trait StreamRepoExt: StreamRepo {
/// Create a durable stream from an async stream.
/// Consumes the async stream and closes the durable stream when it ends.
@@ -17,7 +15,6 @@ pub trait StreamRepoExt: StreamRepo {
id: StreamId,
stream: PayloadStream,
timeout: Option<Duration>,
- close_delay: Option<Duration>,
);
}
@@ -33,27 +30,20 @@ where
id: StreamId,
mut stream: PayloadStream,
timeout: Option<Duration>,
- close_delay: Option<Duration>,
) {
let writer = self.clone();
let writer_id = id.clone();
tokio::spawn(async move {
- let consumed =
- tokio::time::timeout(timeout.unwrap_or(DEFAULT_STREAM_TIMEOUT), async move {
- while let Some(payload) = stream.next().await {
- if let Err(e) = writer.append(&writer_id, payload).await {
- tracing::error!(error=?e, "failed to append to stream");
- break;
- }
+ let _ = tokio::time::timeout(timeout.unwrap_or(DEFAULT_STREAM_TIMEOUT), async move {
+ while let Some(payload) = stream.next().await {
+ if let Err(e) = writer.append(&writer_id, payload).await {
+ tracing::error!(error=?e, "failed to append to stream");
+ break;
}
- })
- .await;
-
- if consumed.is_ok() {
- tokio::time::sleep(close_delay.unwrap_or(DEFAULT_CLOSE_DELAY)).await;
- } else {
- tracing::error!("stream timed out");
- }
+ }
+ })
+ .await
+ .inspect_err(|_| tracing::error!("stream timed out"));
let _ = self
.close(&id)
diff --git a/rust/cloud-storage/stream/src/domain/traits.rs b/rust/cloud-storage/stream/src/domain/traits.rs
index fa0d41a7df..96a77ef68e 100644
--- a/rust/cloud-storage/stream/src/domain/traits.rs
+++ b/rust/cloud-storage/stream/src/domain/traits.rs
@@ -4,6 +4,7 @@ use super::{StreamId, StreamItem};
use async_trait::async_trait;
use futures::stream::Stream;
use std::pin::Pin;
+use std::sync::Arc;
use std::time::Duration;
use tokio::sync::broadcast::Receiver;
@@ -30,8 +31,8 @@ pub trait StreamRepo: Send + Sync + 'static {
async fn close(&self, id: &StreamId) -> Result<()>;
/// List active streams for an entity (implementations may treat all streams as active).
async fn active_streams(&self, entity_id: &str) -> Result<Vec<StreamId>>;
- /// A receiver that receives StreamId's when new streams are created
- async fn notify(&self) -> Receiver<StreamId>;
+ /// A receiver that receives stream lifecycle events.
+ async fn notify(&self) -> Receiver<StreamEvent>;
}
/// Subscribe to all streams on an entity, returning a merged item stream.
@@ -43,4 +44,6 @@ pub trait StreamManager: Send + Sync + 'static {
async fn subscribe(&self, sender_id: String, entity_id: String) -> Result<ItemStream>;
/// Cancel the subscription for the given sender, stopping its stream.
async fn unsubscribe(&self, sender_id: String) -> Result<()>;
+ /// access to the lower-level repo api
+ fn repo(&self) -> Arc<dyn StreamRepo>;
}
diff --git a/rust/cloud-storage/stream/src/domain/types.rs b/rust/cloud-storage/stream/src/domain/types.rs
index 21407ff8d3..87be697734 100644
--- a/rust/cloud-storage/stream/src/domain/types.rs
+++ b/rust/cloud-storage/stream/src/domain/types.rs
@@ -1,8 +1,9 @@
use model_entity::EntityType;
use serde::{Deserialize, Serialize};
use thiserror::Error;
+use utoipa::ToSchema;
-#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
+#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct StreamId {
pub entity_type: EntityType,
pub entity_id: String,
@@ -11,7 +12,27 @@ pub struct StreamId {
pub type Result<T> = std::result::Result<T, StreamServiceError>;
-#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
+/// Events published through the notification channel.
+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
+#[non_exhaustive]
+#[serde(rename_all = "snake_case", tag = "type")]
+pub enum StreamEvent {
+ /// A new stream was created.
+ Created(StreamId),
+ /// A stream was closed.
+ Closed(StreamId),
+}
+
+impl StreamEvent {
+ pub fn id(&self) -> &StreamId {
+ match self {
+ Self::Created(id) => id,
+ Self::Closed(id) => id,
+ }
+ }
+}
+
+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
pub struct StreamItem {
pub id: StreamId,
pub payload: serde_json::Value,
diff --git a/rust/cloud-storage/stream/src/outbound/redis_pg/manager.rs b/rust/cloud-storage/stream/src/outbound/redis_pg/manager.rs
index c760dfba02..3a53de9226 100644
--- a/rust/cloud-storage/stream/src/outbound/redis_pg/manager.rs
+++ b/rust/cloud-storage/stream/src/outbound/redis_pg/manager.rs
@@ -1,4 +1,4 @@
-use crate::domain::{ItemStream, Result, StreamManager, StreamRepo};
+use crate::domain::{ItemStream, Result, StreamEvent, StreamManager, StreamRepo};
use async_stream::stream;
use async_trait::async_trait;
use dashmap::DashMap;
@@ -24,6 +24,10 @@ impl RedisPostgresStreamManager {
#[async_trait]
impl StreamManager for RedisPostgresStreamManager {
+ fn repo(&self) -> Arc<dyn StreamRepo> {
+ self.repo.clone()
+ }
+
#[tracing::instrument(err, skip(self))]
async fn subscribe(&self, sender_id: String, entity_id: String) -> Result<ItemStream> {
let repo = self.repo.clone();
@@ -52,7 +56,7 @@ impl StreamManager for RedisPostgresStreamManager {
}
notification = notify_rx.recv() => {
match notification {
- Ok(stream_id) if stream_id.entity_id == entity_id => {
+ Ok(StreamEvent::Created(stream_id)) if stream_id.entity_id == entity_id => {
match repo.stream_from_beginning(&stream_id).await {
Ok(stream) => merged.push(stream),
Err(e) => {
diff --git a/rust/cloud-storage/stream/src/outbound/redis_pg/repo.rs b/rust/cloud-storage/stream/src/outbound/redis_pg/repo.rs
index e1fcf99055..7d8dcd6109 100644
--- a/rust/cloud-storage/stream/src/outbound/redis_pg/repo.rs
+++ b/rust/cloud-storage/stream/src/outbound/redis_pg/repo.rs
@@ -25,7 +25,7 @@ enum StoredStreamItem {
struct StreamNotifier {
_listener: JoinHandle<()>,
- tx: broadcast::Sender<StreamId>,
+ tx: broadcast::Sender<StreamEvent>,
}
impl StreamNotifier {
@@ -41,11 +41,11 @@ impl StreamNotifier {
}
}
- pub fn subscribe(&self) -> Receiver<StreamId> {
+ pub fn subscribe(&self) -> Receiver<StreamEvent> {
self.tx.subscribe()
}
- fn spawn_subscriber(client: Client, tx: broadcast::Sender<StreamId>) -> JoinHandle<()> {
+ fn spawn_subscriber(client: Client, tx: broadcast::Sender<StreamEvent>) -> JoinHandle<()> {
tracing::info!("Start notification subscriber");
tokio::spawn(async move {
loop {
@@ -56,16 +56,16 @@ impl StreamNotifier {
}
let mut stream = pubsub.on_message();
while let Some(msg) = stream.next().await {
- if let Ok(stream_id) = msg
+ if let Ok(event) = msg
.get_payload::<String>()
.map_err(StreamServiceError::from)
.and_then(|payload| {
- serde_json::from_str::<StreamId>(&payload).map_err(Into::into)
+ serde_json::from_str::<StreamEvent>(&payload).map_err(Into::into)
})
.inspect_err(|err| tracing::error!(error=?err, "failed to get notification payload"))
{
- tracing::debug!(stream_id=?stream_id, "notify new stream");
- let _ = tx.send(stream_id).inspect_err(
+ tracing::debug!(event=?event, "stream event received");
+ let _ = tx.send(event).inspect_err(
|err| tracing::error!(error=?err, "failed to forward notification"),
);
}
@@ -167,7 +167,8 @@ impl StreamRepo for RedisPostgresStreamRepo {
if is_new {
tracing::debug!(stream_id=?id, "New stream detected publishing notification");
- let notification = serde_json::to_string(id).expect("json");
+ let event = StreamEvent::Created(id.clone());
+ let notification = serde_json::to_string(&event).expect("json");
let _: RedisResult<()> = conn
.publish(NOTIFY_CHANNEL, notification)
.await
@@ -262,6 +263,13 @@ impl StreamRepo for RedisPostgresStreamRepo {
.await
.inspect_err(|e| tracing::error!(error=?e, "failed to remove stream from postgres"));
+ let event = StreamEvent::Closed(id.clone());
+ let notification = serde_json::to_string(&event).expect("json");
+ let _: RedisResult<()> = conn
+ .publish(NOTIFY_CHANNEL, notification)
+ .await
+ .inspect_err(|e| tracing::error!(error=?e, "failed to publish close event"));
+
Ok(())
}
@@ -275,7 +283,7 @@ impl StreamRepo for RedisPostgresStreamRepo {
.map_err(|e| StreamServiceError::StorageError(e.to_string()))
}
- async fn notify(&self) -> Receiver<StreamId> {
+ async fn notify(&self) -> Receiver<StreamEvent> {
self.notifier
.get_or_init(|| StreamNotifier::new(&self.redis_client))
.await
diff --git a/rust/cloud-storage/stream/src/outbound/redis_pg/test/manager.rs b/rust/cloud-storage/stream/src/outbound/redis_pg/test/manager.rs
index ceaf3afb87..2c684b1972 100644
--- a/rust/cloud-storage/stream/src/outbound/redis_pg/test/manager.rs
+++ b/rust/cloud-storage/stream/src/outbound/redis_pg/test/manager.rs
@@ -493,7 +493,7 @@ async fn util_test_stream_exhausted(
let items: Vec<serde_json::Value> = (1..=3).map(|i| serde_json::json!({"seq": i})).collect();
let input_stream = futures::stream::iter(items.clone());
- service.from_async_stream(stream_id.clone(), Box::pin(input_stream), None, None);
+ service.from_async_stream(stream_id.clone(), Box::pin(input_stream), None);
let mut count = 0;
while let Ok(Some(_)) = tokio::time::timeout(Duration::from_millis(1000), stream.next()).await {
diff --git a/rust/cloud-storage/stream/src/outbound/redis_pg/test/repo.rs b/rust/cloud-storage/stream/src/outbound/redis_pg/test/repo.rs
index 18989e4b41..a133557a85 100644
--- a/rust/cloud-storage/stream/src/outbound/redis_pg/test/repo.rs
+++ b/rust/cloud-storage/stream/src/outbound/redis_pg/test/repo.rs
@@ -1,5 +1,5 @@
use super::util::StreamGuard;
-use crate::domain::StreamRepoExt;
+use crate::domain::{StreamEvent, StreamRepoExt};
use futures::StreamExt;
use serial_test::serial;
use std::time::Duration;
@@ -72,7 +72,7 @@ async fn test_from_async_stream() {
let input_stream = futures::stream::iter(items.clone());
service
.clone()
- .from_async_stream(stream_id.clone(), Box::pin(input_stream), None, None);
+ .from_async_stream(stream_id.clone(), Box::pin(input_stream), None);
let mut output_stream = service
.stream_from_beginning(&stream_id)
@@ -110,10 +110,13 @@ async fn test_notify_on_multiple_new_streams() {
.await
.expect("Failed to append to stream 1");
- let notified = tokio::time::timeout(timeout, notify.recv())
+ let event = tokio::time::timeout(timeout, notify.recv())
.await
.expect("Timeout waiting for notification on first stream")
.expect("Notify channel closed");
+ let StreamEvent::Created(notified) = event else {
+ panic!("Expected Created event");
+ };
assert_eq!(notified.entity_id, stream_id1.entity_id);
// Second stream creation - should notify
@@ -122,10 +125,13 @@ async fn test_notify_on_multiple_new_streams() {
.await
.expect("Failed to append to stream 2");
- let notified = tokio::time::timeout(timeout, notify.recv())
+ let event = tokio::time::timeout(timeout, notify.recv())
.await
.expect("Timeout waiting for notification on second stream")
.expect("Notify channel closed");
+ let StreamEvent::Created(notified) = event else {
+ panic!("Expected Created event");
+ };
assert_eq!(notified.entity_id, stream_id2.entity_id);
}
@@ -144,10 +150,13 @@ async fn test_notify_only_on_new_stream() {
.expect("Failed to append first item");
let timeout = Duration::from_millis(500);
- let notified_id = tokio::time::timeout(timeout, notify.recv())
+ let event = tokio::time::timeout(timeout, notify.recv())
.await
.expect("Timeout waiting for notification on new stream")
.expect("Notify channel closed");
+ let StreamEvent::Created(notified_id) = event else {
+ panic!("Expected Created event");
+ };
assert_eq!(notified_id.entity_id, stream_id.entity_id);
assert_eq!(notified_id.stream_id, stream_id.stream_id);