streaming.ts 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. import { OpencodeError } from './error';
  2. import { type ReadableStream } from '../internal/shim-types';
  3. import { makeReadableStream } from '../internal/shims';
  4. import { findDoubleNewlineIndex, LineDecoder } from '../internal/decoders/line';
  5. import { ReadableStreamToAsyncIterable } from '../internal/shims';
  6. import { isAbortError } from '../internal/errors';
  7. import { encodeUTF8 } from '../internal/utils/bytes';
  8. import { loggerFor } from '../internal/utils/log';
  9. import type { Opencode } from '../client';
  10. type Bytes = string | ArrayBuffer | Uint8Array | null | undefined;
  11. export type ServerSentEvent = {
  12. event: string | null;
  13. data: string;
  14. raw: string[];
  15. };
  16. export class Stream<Item> implements AsyncIterable<Item> {
  17. controller: AbortController;
  18. #client: Opencode | undefined;
  19. constructor(
  20. private iterator: () => AsyncIterator<Item>,
  21. controller: AbortController,
  22. client?: Opencode,
  23. ) {
  24. this.controller = controller;
  25. this.#client = client;
  26. }
  27. static fromSSEResponse<Item>(
  28. response: Response,
  29. controller: AbortController,
  30. client?: Opencode,
  31. ): Stream<Item> {
  32. let consumed = false;
  33. const logger = client ? loggerFor(client) : console;
  34. async function* iterator(): AsyncIterator<Item, any, undefined> {
  35. if (consumed) {
  36. throw new OpencodeError('Cannot iterate over a consumed stream, use `.tee()` to split the stream.');
  37. }
  38. consumed = true;
  39. let done = false;
  40. try {
  41. for await (const sse of _iterSSEMessages(response, controller)) {
  42. try {
  43. yield JSON.parse(sse.data);
  44. } catch (e) {
  45. logger.error(`Could not parse message into JSON:`, sse.data);
  46. logger.error(`From chunk:`, sse.raw);
  47. throw e;
  48. }
  49. }
  50. done = true;
  51. } catch (e) {
  52. // If the user calls `stream.controller.abort()`, we should exit without throwing.
  53. if (isAbortError(e)) return;
  54. throw e;
  55. } finally {
  56. // If the user `break`s, abort the ongoing request.
  57. if (!done) controller.abort();
  58. }
  59. }
  60. return new Stream(iterator, controller, client);
  61. }
  62. /**
  63. * Generates a Stream from a newline-separated ReadableStream
  64. * where each item is a JSON value.
  65. */
  66. static fromReadableStream<Item>(
  67. readableStream: ReadableStream,
  68. controller: AbortController,
  69. client?: Opencode,
  70. ): Stream<Item> {
  71. let consumed = false;
  72. async function* iterLines(): AsyncGenerator<string, void, unknown> {
  73. const lineDecoder = new LineDecoder();
  74. const iter = ReadableStreamToAsyncIterable<Bytes>(readableStream);
  75. for await (const chunk of iter) {
  76. for (const line of lineDecoder.decode(chunk)) {
  77. yield line;
  78. }
  79. }
  80. for (const line of lineDecoder.flush()) {
  81. yield line;
  82. }
  83. }
  84. async function* iterator(): AsyncIterator<Item, any, undefined> {
  85. if (consumed) {
  86. throw new OpencodeError('Cannot iterate over a consumed stream, use `.tee()` to split the stream.');
  87. }
  88. consumed = true;
  89. let done = false;
  90. try {
  91. for await (const line of iterLines()) {
  92. if (done) continue;
  93. if (line) yield JSON.parse(line);
  94. }
  95. done = true;
  96. } catch (e) {
  97. // If the user calls `stream.controller.abort()`, we should exit without throwing.
  98. if (isAbortError(e)) return;
  99. throw e;
  100. } finally {
  101. // If the user `break`s, abort the ongoing request.
  102. if (!done) controller.abort();
  103. }
  104. }
  105. return new Stream(iterator, controller, client);
  106. }
  107. [Symbol.asyncIterator](): AsyncIterator<Item> {
  108. return this.iterator();
  109. }
  110. /**
  111. * Splits the stream into two streams which can be
  112. * independently read from at different speeds.
  113. */
  114. tee(): [Stream<Item>, Stream<Item>] {
  115. const left: Array<Promise<IteratorResult<Item>>> = [];
  116. const right: Array<Promise<IteratorResult<Item>>> = [];
  117. const iterator = this.iterator();
  118. const teeIterator = (queue: Array<Promise<IteratorResult<Item>>>): AsyncIterator<Item> => {
  119. return {
  120. next: () => {
  121. if (queue.length === 0) {
  122. const result = iterator.next();
  123. left.push(result);
  124. right.push(result);
  125. }
  126. return queue.shift()!;
  127. },
  128. };
  129. };
  130. return [
  131. new Stream(() => teeIterator(left), this.controller, this.#client),
  132. new Stream(() => teeIterator(right), this.controller, this.#client),
  133. ];
  134. }
  135. /**
  136. * Converts this stream to a newline-separated ReadableStream of
  137. * JSON stringified values in the stream
  138. * which can be turned back into a Stream with `Stream.fromReadableStream()`.
  139. */
  140. toReadableStream(): ReadableStream {
  141. const self = this;
  142. let iter: AsyncIterator<Item>;
  143. return makeReadableStream({
  144. async start() {
  145. iter = self[Symbol.asyncIterator]();
  146. },
  147. async pull(ctrl: any) {
  148. try {
  149. const { value, done } = await iter.next();
  150. if (done) return ctrl.close();
  151. const bytes = encodeUTF8(JSON.stringify(value) + '\n');
  152. ctrl.enqueue(bytes);
  153. } catch (err) {
  154. ctrl.error(err);
  155. }
  156. },
  157. async cancel() {
  158. await iter.return?.();
  159. },
  160. });
  161. }
  162. }
  163. export async function* _iterSSEMessages(
  164. response: Response,
  165. controller: AbortController,
  166. ): AsyncGenerator<ServerSentEvent, void, unknown> {
  167. if (!response.body) {
  168. controller.abort();
  169. if (
  170. typeof (globalThis as any).navigator !== 'undefined' &&
  171. (globalThis as any).navigator.product === 'ReactNative'
  172. ) {
  173. throw new OpencodeError(
  174. `The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`,
  175. );
  176. }
  177. throw new OpencodeError(`Attempted to iterate over a response with no body`);
  178. }
  179. const sseDecoder = new SSEDecoder();
  180. const lineDecoder = new LineDecoder();
  181. const iter = ReadableStreamToAsyncIterable<Bytes>(response.body);
  182. for await (const sseChunk of iterSSEChunks(iter)) {
  183. for (const line of lineDecoder.decode(sseChunk)) {
  184. const sse = sseDecoder.decode(line);
  185. if (sse) yield sse;
  186. }
  187. }
  188. for (const line of lineDecoder.flush()) {
  189. const sse = sseDecoder.decode(line);
  190. if (sse) yield sse;
  191. }
  192. }
  193. /**
  194. * Given an async iterable iterator, iterates over it and yields full
  195. * SSE chunks, i.e. yields when a double new-line is encountered.
  196. */
  197. async function* iterSSEChunks(iterator: AsyncIterableIterator<Bytes>): AsyncGenerator<Uint8Array> {
  198. let data = new Uint8Array();
  199. for await (const chunk of iterator) {
  200. if (chunk == null) {
  201. continue;
  202. }
  203. const binaryChunk =
  204. chunk instanceof ArrayBuffer ? new Uint8Array(chunk)
  205. : typeof chunk === 'string' ? encodeUTF8(chunk)
  206. : chunk;
  207. let newData = new Uint8Array(data.length + binaryChunk.length);
  208. newData.set(data);
  209. newData.set(binaryChunk, data.length);
  210. data = newData;
  211. let patternIndex;
  212. while ((patternIndex = findDoubleNewlineIndex(data)) !== -1) {
  213. yield data.slice(0, patternIndex);
  214. data = data.slice(patternIndex);
  215. }
  216. }
  217. if (data.length > 0) {
  218. yield data;
  219. }
  220. }
  221. class SSEDecoder {
  222. private data: string[];
  223. private event: string | null;
  224. private chunks: string[];
  225. constructor() {
  226. this.event = null;
  227. this.data = [];
  228. this.chunks = [];
  229. }
  230. decode(line: string) {
  231. if (line.endsWith('\r')) {
  232. line = line.substring(0, line.length - 1);
  233. }
  234. if (!line) {
  235. // empty line and we didn't previously encounter any messages
  236. if (!this.event && !this.data.length) return null;
  237. const sse: ServerSentEvent = {
  238. event: this.event,
  239. data: this.data.join('\n'),
  240. raw: this.chunks,
  241. };
  242. this.event = null;
  243. this.data = [];
  244. this.chunks = [];
  245. return sse;
  246. }
  247. this.chunks.push(line);
  248. if (line.startsWith(':')) {
  249. return null;
  250. }
  251. let [fieldname, _, value] = partition(line, ':');
  252. if (value.startsWith(' ')) {
  253. value = value.substring(1);
  254. }
  255. if (fieldname === 'event') {
  256. this.event = value;
  257. } else if (fieldname === 'data') {
  258. this.data.push(value);
  259. }
  260. return null;
  261. }
  262. }
  263. function partition(str: string, delimiter: string): [string, string, string] {
  264. const index = str.indexOf(delimiter);
  265. if (index !== -1) {
  266. return [str.substring(0, index), delimiter, str.substring(index + delimiter.length)];
  267. }
  268. return [str, '', ''];
  269. }