Skip to content

feat: Streaming Mutations / Queries #4477

Closed

Description

@iamnafets

Describe the feature you'd like to request

Many upstream APIs (e.g. OpenAI's GPT) stream responses to the client. It would be great if TRPC supported such streaming requests.

Describe the solution you'd like to see

I'd imagine this would look like a mutation or query where the resolver is an async generator. Example:

publicProcedure
   .streamingMutation(async function* ({ input, ctx }) {
     for(let x=0x;<10;x++) {
       yield x;
       await sleep(100);
     }
   });

Describe alternate solutions

An alternative is to set up subscriptions and map the mutation inputs to some identifier in the subscription. The problem with this approach is (a) it depends on websockets, which are difficult to support from an infrastructure perspective, (b) the race conditions between establishing a socket connection and corresponding this with mutations/queries can be miserable.

Additional information

I'd mostly like to understand any suggestions for how to approach this and whether you'd support a PR. Creating a streamingMutation procedure type, for instance, is fairly invasive but may be the correct approach.

👨‍👧‍👦 Contributing

  • 🙋‍♂️ Yes, I'd be down to file a PR implementing this feature!
### Tasks

Activity

  1. Sheraff commented on Jun 3, 2023

    @Sheraff
    Contributor

    I do like the idea, but I can't wrap my head around the ergonomics of consuming such a procedure. Here are my thoughts so far.


    Do you have an idea of the API you'd like for the client consuming such a request?

    With the classic react-query api, we'd receive a data object

    const { data } = trpc.name.useQuery()

    So, not considering implementation feasibility, what would this data object look like?

    Say the server is yielding a few results

    yield { foo: 1 }
    yield { foo: 2 } 
    yield { foo: 3 }

    Should we re-render on every chunk of the stream? This could mean that data is an array of results, and we re-render potentially many times in a few milliseconds:

    data = [{ foo: 1 }] // first render
    data = [{ foo: 1 }, { foo: 2 }] // second render
    data = [{ foo: 1 }, { foo: 2 }, { foo: 3 }] // third render

    Or should we use promises instead? Since we can't know you many times the generator will yield, it would be a tuplet of [data, promise] with nested promises for subsequent yields...

    data = [
      {foo: 1},
      Promise.resolve([
        { foo: 2 },
        Promise.resolve([
          { foo: 3 }
        ])
      ])
    ]

    This was a basic example where we're yielding a series of items, so it fits well into an array or some sort or recursive pattern. But should a "streaming procedure" handle any sort of async data?

    What about a procedure that returns this sort of data:

    return {
      foo: Promise.resolve(1),
      bar: {
        a: 1,
        b: Promise.resolve(2),
      },
      baz: Promise.resolve({
        c: 1,
        d: Promise.resolve(2),
      })
    }

    Would we handle promises as returned values? Only at the first level (foo) or deeper too (bar.b)? And should we handle nesting (baz.d)?

    If we want to handle any of these cases, what should the API look like for a client consuming this endpoint?

  2. iamnafets commented on Jun 3, 2023

    @iamnafets
    ContributorAuthor

    There are indeed lots of options! There's several use-cases buried so I think working backwards from them makes sense:

    1. Multiple Hydration - In these use cases, we may have a multiple incomplete versions of a final object which are delivered before the fully hydrated final version. For this, I think useQuery or useMutation directly make sense:
    publicProcedure.
      query(({ input, ctx }) => {
        let result = {
           foo: undefined,
           bar: undefined
           stage: 1
        }
        yield result;
        // ... waiting
        result.foo = "foo";
        result.stage = 2;
        yield result;
        // ... waiting
        result.bar = "bar";
        result.stage = 3;
        yield result;
      }

    For this, on the client would look exactly like today except the results might be updated multiple times. I believe reactQuery supports this natively via setQueryData. Example here: TanStack/query#418 (comment)

    1. Streaming Arrays / Short-Lived Subscription - this is pretty typical for transcription or generative use-cases (like the OpenAI API). I think this is best supported with a subscription-like observable (onData, etc) but via HTTP and with a singular procedure. The way we currently hack this today is to maintain a reference to the subscription connection that is then used by the query/mutation to push results -- quite hacky.
  3. Sheraff commented on Jun 3, 2023

    @Sheraff
    Contributor

    Your 1st option seems nice in terms of developer experience, but, naively, would result in sending many times the same object over the wire...

    Maybe (big grain of salt here, I've only done a single PR on this project!) something like this would work:

    t.query(function*() {
      const bar = new TRPCDeferred<string>()
      const stage = new TRPCDeferred<number>(1)
      yield {
        foo: "hello",
        bar,
        stage,
      }
      // ... waiting
      bar.set("bar")
      stage.set(2)
      yield
      // ... waiting
      stage.set(3)
      yield
    })

    Or maybe more realistically:

    t.query(() => {
      const barPromise = Promise.resolve("bar")
      const bar = new TRPCDeferred(barPromise)
      return {
        foo: "hello",
        bar,
      }
    })

    But since the use cases are close to each other, I'd love a single API.

    Also, I'm not 100% sold on the many re-renders of the same data object though it is indeed possible with react-query. The onus would have to be on the devs to make sure streaming is worth it for their use case and they're not shooting themselves in the foot.

  4. Sheraff commented on Jun 3, 2023

    @Sheraff
    Contributor

    @helmturner you might be interested in this

  5. helmturner commented on Jun 4, 2023

    @helmturner

    First off, I think we should definitely rope in the folks (@leonwilly @timcole @OutdatedVersion) that have done similar work over in #544, of which this actually appears to be a duplicate...?

    Should we re-render on every chunk of the stream? This could mean that data is an array of results, and we re-render potentially many times in a few milliseconds:

    Generally, React is pretty optimized for rendering and people tend to be over-concerned with limiting re-renders. If there is an edge case where performance degradation occurs, I would second the notion that the onus should be on the developer to optimize where necessary.

    I've just published @alecvision/trpc-sse-link and @alecvision/trpc-sse-adapter to NPM, those links point to the OSS repos here on GH. As of writing, it's pretty hack-y and it needs a cleanup. I basically repurposed some of the source code for the fetch adapter and http links, but it proves the concept. It's a naive solution, but there may be some interesting ideas on how we can minimize the lift on this feature.

    I'm going to do some serious cleanup in the next 24h or so, but if you want to check out the README it shows the concepts. The source code will be more review-friendly by mid week.

  6. helmturner commented on Jun 4, 2023

    @helmturner

    Just realizing that this post went in the wrong place, so quoting here (from #4347):

    It's largely based off of the HTTP link and fetch adapter, but I'm using subscription procedures and applying a bit of a hack to route requests around the websocket link (pattern-matching procedures, which requires the hack to be applied in both the server and client configs).

    The only clean API I could think of involves adding a new procedure type with the exact same semantics as a subscription, but that uses a header or HTTP method (I'm using both, and I picked PATCH). Requests that include the correct method or header are then routed through a link/adapter like the one I hacked together.

  7. helmturner commented on Jun 4, 2023

    @helmturner

    I'm noticing dropped events in my implementation, as well as bad error handling on server errors. If you spot / can think of any other shortcomings please let me know 👍

  8. StringKe commented on Jun 5, 2023

    @StringKe

    I'm noticing dropped events in my implementation, as well as bad error handling on server errors. If you spot / can think of any other shortcomings please let me know 👍

    Doesn't seem to handle browser disconnect events?

    I tried to use request.socket.on("close") but I can't listen to the browser active disconnect event, does your code have this problem?

  9. helmturner commented on Jun 6, 2023

    @helmturner

    So I'm starting to get a pretty good feel for the internals, and updating my libraries for compatibility with 10.29 is going to help me grok some of the stuff I was fuzzy on††. Along with all of the other great work, I think we've got a lot of good options on how to do this. The subscription route is the easiest to hack together as a monkey-patch, but...

    I have an idea for an API that I think adheres to the 'principle of least surprise.' Essentially, the idea is that returning an async iterable from a query or mutation would:

    • Patch the Router type shared across the boundary to wrap those procedures with a Streamable<TProcedure> type
    • Patch the options signature for the appropriate .use<...> hook to include an option for an onChunk callback†
    • The client indicates streaming is enabled via the request URL‡
    • On the server, Chunks are generated by iterating over the procedure result (i.e. for await (const chunk of result) { })
    • On the client, the onChunk callback is called for each chunk received
    • The query or mutation resolves, as normal, with the data property set to the procedure result. (We unwrap it from the iterable and maybe delete the property, too?)
    • (Optional) maybe we include a default polyfill for the EventSource/TextDecoder APIs on the client (for React Native)?

    If I have any idea what I'm talking about, and it works, we get these benefits:

    • Streaming can be opt-in on the client, gracefully falling back to the current behavior
    • It wouldn't require a new procedure type
    • It wouldn't require a new link (I think)
    • It wouldn't require rerouting subscriptions around the WebSockets link
    • It would separate the semantics for fully resolved results from that of partial chunks

    Am I missing something? What do y'all think of that API? I'm not sure of the implementation details exactly, but it seems pretty doable from what I can tell so far. I can do some playing around with it - I'm still wrapping my head around the httpBatchStreamLink PR.

    Also, I'm not sure if the httpBatchStreamLink implements a shared stream per @timcole's comment on the other thread, but that should certainly be done as well if we can manage.

    † I think onStart and onError are covered by isFetching, isError, and other state utils from React Query...?

    ‡ Originally I thought header or method, but that assumes a 1-to-1 relationship between procedure calls and requests, which would rule out batching

    †† PS, @Sheraff thanks for your awesome work on the httpBatchStreamLink. The link/adapter I made is both my first time working with SSE and my first time working with tRPC internals, so your recent PR has been the perfect learning example!

  10. iamnafets commented on Jun 6, 2023

    @iamnafets
    ContributorAuthor

    I threw together some of these ideas in #4489 @helmturner . It's pretty messy but I think it touches on several of the same ideas you mention above. In particular, I love having an async generator as the body of query and mutation and having this gracefully fall back.

    I completely abuse @Sheraff 's streaming HTTP link for this, probably in ways that are incompatible with other non-streaming links. I'll have to think through some test cases.

    The part I don't like about this is it's opaque to the client whether the underlying is actually a generator or a simple promise. I'd prefer to expose only mutateGenerator (or even a mutate with the proper return type) if the implementation is actually a generator.

    I haven't bothered with migrating subscriptions over to this model but in theory you could do so with some client-side magic to cue up a continuation request after a fixed duration (probably < 60s as most load balancers end up hanging up the socket).

    Anyways, I'm open to iterating on the PR I linked or starting a new one with this as a reference. I'm intending to use this code in production to start to iron out remaining issues but if there is a modestly API-compatible fork/alternative, I'm all for it.

  11. helmturner commented on Jun 6, 2023

    @helmturner

    Damn @iamnafets, I was literally going to go to bed after I finished that comment lol. I'll have to check out your PR tomorrow.

    But RE: subscriptions, I think it makes a lot of sense to leave them alone if we implement this in query/mutation land. I can't think of a unidirectional subscription use-case that would be served by the subscription API which isn't served by this theoretical streaming API. Plus, WS is a whole different protocol - it makes sense to need special handling for that, i.e. WSLink and a separate WS server. But if we can bring these features to the HTTP based APIs in a non-intrusive way, this feature could potentially "Just Work™️" with no additional configuration needed.

    Also, I believe my idea above solves the client opacity problem. An AsyncIterable doesn't have to yield the same type of value that it returns:

    interface AsyncIterator<T, TReturn = any, TNext = undefined> {
        // NOTE: 'next' is defined using a tuple to ensure we report the correct assignability errors in all places.
        next(...args: [] | [TNext]): Promise<IteratorResult<T, TReturn>>;
        return?(value?: TReturn | PromiseLike<TReturn>): Promise<IteratorResult<T, TReturn>>;
        throw?(e?: any): Promise<IteratorResult<T, TReturn>>;
    }

    So basically, the value returned by next() on the server is passed to onChunk on the client, and the value returned by return() on the server is the value of data on the client. For non-streaming consumers, the client can act like the streaming API isn't even there... It's all abstracted away behind a single callback on the client and a AsyncIterable return value on the server.

    All we would have to do when resolving is check if the procedure result has a Symbol.asyncIterator property. If so, use it to resolve the request (either eagerly via SSE if a Accept: text/event-stream header is passed, or just plain-old res.json() if not).

  12. StringKe commented on Jun 6, 2023

    @StringKe

    I don't quite understand how the back-end Generator should handle it when the client closes the connection.

  13. helmturner commented on Jun 6, 2023

    @helmturner

    @iamnafets What are the pros/cons of defining the resolver as an async generator, as opposed to making it the return value of a normal resolver function? I'm genuinely asking... are they basically equivalent? How do the semantics of your implementation differ from my description above?

    @StringKe I don't get what you mean I think. Any intentional disconnects should be handled by the AbortController API, and for unintentional disconnects, the EventSource API handles reconnects automatically when event IDs are provided.

  14. Sheraff commented on Jun 6, 2023

    @Sheraff
    Contributor

    I think you might be getting a little too preoccupied with the implementation details (which are quite fun I agree, it's not every day that we have a genuine use-case for generators and HTTP streaming).

    Could we have a clear description of what the experience will be from the point of view of a dev using the tRPC library? I think once this is nailed down and we have a clear understanding of what we want to do, then we can talk about the best implementation.

  15. 37 remaining items

  16. StringKe commented on Jun 8, 2023

    @StringKe

    yes

    in fastify doces:

    You can listen to the request close event and determine if the request was aborted or if it was successfully delivered. You can implement this solution in an onRequest hook or directly in an individual route.

    does not work in nextjs.

  17. helmturner commented on Jun 8, 2023

    @helmturner

    I see, that's a bummer. I hope they can get that fixed soon... Have you tried implementing this on an edge route? I wonder if the bug is specific to the Node runtime. Also, are you using an EventSource client to manage the SSE connection?

  18. StringKe commented on Jun 8, 2023

    @StringKe

    I see, that's a bummer. I hope they can get that fixed soon... Have you tried implementing this on an edge route? I wonder if the bug is specific to the Node runtime. Also, are you using an EventSource client to manage the SSE connection?

    I didn't try edge routers I don't use it.

    I do use EventSource to open SSE connections.

    with-sse.ts

    import { TRPCError, type AnyProcedure, type AnyRouter } from '@trpc/server'
    import { createNextApiHandler } from '@trpc/server/adapters/next'
    import { type NodeHTTPHandlerOptions } from '@trpc/server/adapters/node-http'
    import { type HTTPRequest } from '@trpc/server/http'
    import { isObservable, type Observable } from '@trpc/server/observable'
    import { transformTRPCResponse } from '@trpc/server/shared'
    import { get } from 'lodash-es'
    import { type NextApiHandler, type NextApiRequest, type NextApiResponse } from 'next/types'
    
    import {
        caughtErrorToData,
        contentTypeHandler,
        getRawProcedureInputOrThrow,
        queryToSearchParams,
        SSEEventMessage,
    } from './utils'
    
    export function withSSE<TRouter extends AnyRouter>(
        opts: NodeHTTPHandlerOptions<TRouter, NextApiRequest, NextApiResponse>,
    ): NextApiHandler {
        const handler: NextApiHandler = createNextApiHandler(opts)
    
        const deserialize = get(opts.router, '_def._config.transformer.input.deserialize') as unknown as (
            rawValue: any,
        ) => any
        const deserializeInputValue = (rawValue: unknown) => {
            return typeof rawValue !== 'undefined' ? deserialize(rawValue) : rawValue
        }
    
        return async (request: NextApiRequest, response: NextApiResponse) => {
            const path = request.query.trpc as string
    
            const procedure = get(opts.router._def.procedures, path) as AnyProcedure | undefined
            const isSubscription = get(procedure, '_def.subscription') === true
    
            if (isSubscription && procedure) {
                const ctx = await opts?.createContext?.({ req: request, res: response })
    
                const query = queryToSearchParams(request.query)
    
                const req: HTTPRequest = {
                    method: request.method || 'get',
                    headers: request.headers,
                    query: query,
                    body: contentTypeHandler.getBody({
                        req: request,
                        res: response,
                        path: path,
                        router: opts.router,
                        query: queryToSearchParams(request.query),
                        maxBodySize: opts.maxBodySize,
                    }),
                }
    
                const rawInput = getRawProcedureInputOrThrow(req)
                const input = deserializeInputValue(rawInput)
                const onTrpcError = (cause: any) => {
                    const { body } = caughtErrorToData(cause, {
                        opts: {
                            req: req,
                            router: opts.router,
                            onError: opts.onError as never,
                        },
                        ctx,
                        type: 'subscription',
                        path: path,
                        input: input,
                    })
                    return body
                }
    
                const onEnd = () => {
                    response.end(SSEEventMessage('end', '{"result":{"data":{"json":{}}}}'))
                }
                const onError = (cause: any) => {
                    response.end(SSEEventMessage('error', onTrpcError(cause)))
                }
    
                response.writeHead(200, {
                    Connection: 'keep-alive',
                    'Content-Encoding': 'none',
                    'Cache-Control': 'no-cache, no-transform',
                    'Content-Type': 'text/event-stream',
                })
    
                response.flushHeaders()
    
                try {
                    const procedureResponse = (await procedure({
                        type: 'subscription',
                        ctx: ctx,
                        path: path,
                        rawInput: input,
                    })) as Observable<any, any>
    
                    if (!isObservable(procedureResponse)) {
                        throw new TRPCError({
                            message: `Subscription ${path} did not return an observable`,
                            code: 'INTERNAL_SERVER_ERROR',
                        })
                    }
    
                    const subscription = procedureResponse.subscribe({
                        next(value: any) {
                            const transformedJSON = transformTRPCResponse(opts.router._def._config, {
                                result: { data: value },
                            })
                            response.write(SSEEventMessage('data', JSON.stringify(transformedJSON)))
                        },
                        error(cause) {
                            onError(cause)
                        },
                        complete() {
                            onEnd()
                        },
                    })
    
                    response.on('close', () => {
                        console.log('response closed')
                        subscription.unsubscribe()
                    })
                    response.on('abort', () => {
                        console.log('response aborted')
                        subscription.unsubscribe()
                    })
                    response.socket?.on('close', () => {
                        console.log('socket closed')
                        subscription.unsubscribe()
                    })
                    response.socket?.on('end', () => {
                        console.log('socket ended')
                        subscription.unsubscribe()
                    })
    
                    request.socket.on('close', () => {
                        console.log('socket closed')
                        subscription.unsubscribe()
                    })
                    request.socket.on('end', () => {
                        console.log('socket ended')
                        subscription.unsubscribe()
                    })
                    request.on('close', () => {
                        console.log('request closed')
                        subscription.unsubscribe()
                    })
                    request.on('end', () => {
                        console.log('request ended')
                        subscription.unsubscribe()
                    })
                    request.on('error', () => console.log('request error'))
                    request.on('pause', () => console.log('request paused'))
                } catch (cause: any) {
                    onError(cause)
                }
                return
            }
    
            return handler(request, response)
        }
    }

    sse-link.ts

    import { TRPCClientError, type TRPCLink } from '@trpc/client'
    import { transformResult } from '@trpc/client/shared'
    import { type AnyRouter } from '@trpc/server'
    import { observable } from '@trpc/server/observable'
    
    import { getUrl } from './utils'
    
    export declare type HttpSSELinkOptions = {
        url: string
        EventSource?: typeof EventSource
    }
    
    export declare type HttpSSELinkOpenContext = {
        url: string
        handleEvent: (data: any) => void
        handleError: (error: MessageEvent<any> | Event) => void
        handleClose: (data: MessageEvent<any>) => void
        handleOpen: () => void
    }
    
    export const httpSseLink = <TRouter extends AnyRouter>(opts: HttpSSELinkOptions): TRPCLink<TRouter> => {
        return (runtime) => {
            const getEventData = (event: MessageEvent<any>) => {
                const data = (event.data || '') as string
                const response = JSON.parse(data) as never
                return transformResult(response, runtime)
            }
    
            const open = ({ url, handleEvent, handleError, handleClose, handleOpen }: HttpSSELinkOpenContext) => {
                const EventSourceClass = opts.EventSource ?? EventSource
                const eventSource = new EventSourceClass(url)
    
                eventSource.onopen = () => {
                    handleOpen()
                }
    
                eventSource.onerror = (error: Event) => {
                    handleError(error)
                }
    
                eventSource.addEventListener('data', (event: MessageEvent<any>) => {
                    handleEvent(event)
                })
    
                eventSource.addEventListener('error', (event: MessageEvent<any>) => {
                    handleError(event)
                })
    
                eventSource.addEventListener('end', (event: MessageEvent<any>) => {
                    handleClose(event)
                })
    
                return {
                    close: () => {
                        eventSource.close()
                    },
                }
            }
    
            return ({ op }) => {
                const { path, input, type } = op
    
                if (type !== 'subscription') {
                    throw new Error('HttpSSELink must use subscription')
                }
    
                return observable((observer) => {
                    const source = open({
                        url: getUrl({
                            url: opts.url,
                            type,
                            path,
                            input,
                            runtime,
                        }),
                        handleEvent: (event) => {
                            const transformed = getEventData(event)
                            if (!transformed.ok) {
                                observer.error(
                                    TRPCClientError.from(transformed.error, {
                                        meta: {},
                                    }),
                                )
                                return
                            }
                            observer.next({ result: transformed.result, context: {} })
                        },
                        handleClose: (event) => {
                            const transformed = getEventData(event)
                            if (!transformed.ok) {
                                observer.error(
                                    TRPCClientError.from(transformed.error, {
                                        meta: {},
                                    }),
                                )
                                return
                            }
                            // observer.next({ result: { type: 'stopped' } })
                            observer.complete()
                        },
                        handleOpen: () => {
                            // observer.next({ result: { type: 'started' } })
                        },
                        handleError: (cause) => {
                            if (cause instanceof MessageEvent) {
                                const transformed = getEventData(cause)
                                if (!transformed.ok) {
                                    observer.error(
                                        TRPCClientError.from(transformed.error, {
                                            meta: {},
                                        }),
                                    )
                                    return
                                }
                            }
                            throw new Error('SSE error', {
                                cause: cause,
                            })
                        },
                    })
    
                    return () => {
                        console.log('close')
                        source.close()
                    }
                })
            }
        }
    }
  19. helmturner commented on Jun 12, 2023

    @helmturner

    @iamnafets @Sheraff

    I think I'm pretty close to having the server parts done, but I wanted to get some feedback on the response formatting. Here's the breakdown I've come up with (replace "response X" and "chunk X" with a properly formatted JSONrpc message)

    Non-stream, non-batch:

    "response #1"

    Non-stream, batch:

    ["response #1", "response #2"]

    JSON stream, non-batch:

    Note It is not possible to know ahead of time if a response is a stream. If the client hints via header
    that it wants a stream, and streaming is enabled on the server, then the server MUST format the response
    as a record of chunks, even if there is only one chunk.

    {"1":"chunk #1__0" // The first yield from the generator, if any
    ,"2":"chunk #1__1"  // The second yield from the generator, if any
    ,"0":"response #1" // Either the response (if not an iterator) or the return value of the iterator.
    }

    JSON stream, batch:

    Note Indexes for chunks begin at the first index after all responses. This guarantees no collisions.
    Also, there is virtually no difference between batch & non-batch streams. All streams are essentially batches
    that include both chunks and responses.

    {"2": "chunk #1__0" // A chunk resolves
    ,"3": "chunk #2__0" // A chunk from another iterator resolves
    ,"4":"chunk #2__1" // The second chunk from the second iterator resolves
    ,"1": "response #2" // The second response resolves
    ,"5":"chunk #1__1" // The second chunk from the first iterator resolves
    ,"0": "response #1" // The first response resolves
    }

    SSE stream, non-batch:

    `data: "{ "result": { "type": "start" } }"
    
    data: "chunk #1__0"
    id: 1
    
    data: "chunk #1__1"
    id: 2
    
    data: "response #1"
    id: 0
    
    data: "{ "result": { "type": "end" } }"`
    

    SSE stream, batch:

    `data: "{ "result": { "type": "start" } }"
    
    data: "chunk #1__0"
    id: 2
    
    data: "chunk #2__0"
    id: 3
    
    data: "chunk #2__1"
    id: 4
    
    data: "response #2
    id: 1
    
    data: "chunk #1__1"
    id: 5
    
    data: "response #1
    id: 0
    
    data: "{ "result": { "type": "end" } }"`
    
  20. helmturner commented on Jun 15, 2023

    @helmturner

    I have an early draft PR up for the server-side changes, but it still needs work. I have it passing 90%+ of tests, but I broke a few things I'll need to look into (probably the same things @Sheraff broke before going the callback route).

    Many changes may still follow - there's a good chance I end up refactoring it to look more like the previous iteration if I struggle much more with the last few tests. I also need to write more unit tests for the new modules.

  21. theogravity commented on Jun 15, 2023

    @theogravity

    I have an early draft PR up for the server-side changes, but it still needs work. I have it passing 90%+ of tests, but I broke a few things I'll need to look into (probably the same things @Sheraff broke before going the callback route).

    Many changes may still follow - there's a good chance I end up refactoring it to look more like the previous iteration if I struggle much more with the last few tests. I also need to write more unit tests for the new modules.

    Do one of the tests deal with the server shutting down mid-stream? I have a fetch-based impl (doesn't use tRPC) and discovered the client conn stays opened if I happen to shut down the server.

    Setting the timeout value on the fetch options didn't seem to help, and will be trying an AbortController to see if it fixes it.

  22. helmturner commented on Jun 15, 2023

    @helmturner

    @theogravity I'll be sure to check for that case. My first goal is to get the existing tests passing so I know I didn't break existing features, but after that, I'll turn my attention to hardening the new feature.

  23. marschr commented on Sep 15, 2023

    @marschr

    What's the status and interest on this as of lately? Is there a latest implementation of something like infiniteQuery or async-gen code? I was looking into #4489 and #4530 but didn't felt conclusive.

    My case is that I'm implementing something similar on sveltekit, already got SSE working thanks to @matannahmani on #544 (much appreciated!), I need my UI to report on the state of long lasting remote calls that are being processed on the server (similar in architecture to the AI-chat/chatGPT examples here), while the server keeps streaming updates to the UI. It's basically a web UI for services running on a remote server. I'm also looking into handling client-disconnects (maybe will need some session IDs to address it, cache it and then resend it when the user reconnects).
    I'm looking forward to sharing anything when I get to a more concrete implementation soon.

  24. matannahmani commented on Sep 15, 2023

    @matannahmani

    @marschr I thought the folks over here were on it but it seems to die out, next weekend I might have a few spare hours to work on it to create a simple wrapper or recipe.
    For now if you want to fix / improve your stream try to follow vercel ai sdk concepts It's relatively easy and it handles most use cases.
    https://sdk.vercel.ai/docs/concepts/backpressure-and-cancellation

  25. KATT commented on Sep 27, 2023

    @KATT
    Member

    Hey - sorry for being slow on this.

    Could you (@helmturner @iamnafets) join our Discord and we can chat more about It there? It's quite a big thing but I like your proposals here

    @ me in the "#-🎏-rfc-streaming"-channel - maybe we should setup a call or something to discuss it

  26. linked a pull request that will close this issueFeat: Streaming #4960on Oct 26, 2023
  27. github-actions commented on May 20, 2024

    @github-actions
    Contributor

    This issue has been locked because we are very unlikely to see comments on closed issues. If you are running into a similar issue, please create a new issue. Thank you.

  28. locked as resolved and limited conversation to collaborators on May 20, 2024
  29. KATT commented on Jul 12, 2024

    @KATT
    Member

    Also see a follow-up issue, #5851, that is now solved

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions