in-memory-output-store.ts 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. import type {
  2. TaskOutputChunk,
  3. TaskOutputKind,
  4. TaskOutputReadOptions,
  5. TaskOutputReadResult,
  6. TaskOutputRef,
  7. TaskOutputStore,
  8. TaskOutputStream,
  9. } from './types.js';
  10. export interface InMemoryTaskOutputStoreOptions {
  11. now?: () => number;
  12. kind?: TaskOutputKind;
  13. uriPrefix?: string;
  14. }
  15. interface OutputRecord {
  16. chunks: TaskOutputChunk[];
  17. summary?: string;
  18. outputRef?: TaskOutputRef;
  19. }
  20. export class InMemoryTaskOutputStore implements TaskOutputStore {
  21. private readonly outputs = new Map<string, OutputRecord>();
  22. private readonly now: () => number;
  23. private readonly kind: TaskOutputKind;
  24. private readonly uriPrefix: string;
  25. constructor(options: InMemoryTaskOutputStoreOptions = {}) {
  26. this.now = options.now ?? Date.now;
  27. this.kind = options.kind ?? 'memory';
  28. this.uriPrefix = options.uriPrefix ?? 'memory://background-task/';
  29. }
  30. async append(chunk: TaskOutputChunk): Promise<TaskOutputRef> {
  31. const record = this.getOrCreate(chunk.taskId);
  32. const stream = chunk.stream ?? 'stdout';
  33. const offset = chunk.offset ?? byteLength(this.getContent(chunk.taskId, stream));
  34. const storedChunk: TaskOutputChunk = {
  35. ...chunk,
  36. stream,
  37. offset,
  38. timestamp: chunk.timestamp ?? this.now(),
  39. metadata: chunk.metadata ? { ...chunk.metadata } : undefined,
  40. };
  41. record.chunks.push(storedChunk);
  42. const outputRef: TaskOutputRef = {
  43. taskId: chunk.taskId,
  44. kind: this.kind,
  45. uri: `${this.uriPrefix}${encodeURIComponent(chunk.taskId)}`,
  46. offset: offset + byteLength(chunk.content),
  47. updatedAt: storedChunk.timestamp,
  48. };
  49. record.outputRef = outputRef;
  50. return { ...outputRef };
  51. }
  52. async read(taskId: string, options: TaskOutputReadOptions = {}): Promise<TaskOutputReadResult> {
  53. const record = this.outputs.get(taskId);
  54. if (!record) {
  55. return { content: '', nextOffset: options.offset ?? 0, outputRef: undefined };
  56. }
  57. const stream = options.stream;
  58. const offset = Math.max(0, options.offset ?? 0);
  59. const content = this.getContent(taskId, stream);
  60. const limit = options.limitBytes;
  61. const slice = sliceUtf8(content, offset, limit);
  62. return {
  63. content: slice.content,
  64. nextOffset: slice.nextOffset,
  65. truncated: slice.truncated,
  66. summary: record.summary,
  67. outputRef: record.outputRef ? { ...record.outputRef } : undefined,
  68. };
  69. }
  70. async tail(taskId: string, limitBytes = 8_192): Promise<TaskOutputReadResult> {
  71. const content = this.getContent(taskId);
  72. const offset = Math.max(0, byteLength(content) - limitBytes);
  73. return this.read(taskId, { offset, limitBytes });
  74. }
  75. async finalize(taskId: string, summary?: string): Promise<void> {
  76. const record = this.getOrCreate(taskId);
  77. record.summary = summary;
  78. }
  79. private getOrCreate(taskId: string): OutputRecord {
  80. let record = this.outputs.get(taskId);
  81. if (!record) {
  82. record = { chunks: [] };
  83. this.outputs.set(taskId, record);
  84. }
  85. return record;
  86. }
  87. private getContent(taskId: string, stream?: TaskOutputStream): string {
  88. const record = this.outputs.get(taskId);
  89. if (!record) return '';
  90. return record.chunks
  91. .filter((chunk) => !stream || (chunk.stream ?? 'stdout') === stream)
  92. .map((chunk) => chunk.content)
  93. .join('');
  94. }
  95. }
  96. function byteLength(content: string): number {
  97. return Buffer.byteLength(content, 'utf8');
  98. }
  99. function sliceUtf8(
  100. content: string,
  101. offset: number,
  102. limitBytes: number | undefined,
  103. ): { content: string; nextOffset: number; truncated: boolean } {
  104. const buffer = Buffer.from(content, 'utf8');
  105. const start = Math.min(offset, buffer.length);
  106. const end =
  107. limitBytes === undefined ? buffer.length : Math.min(buffer.length, start + limitBytes);
  108. return {
  109. content: buffer.subarray(start, end).toString('utf8'),
  110. nextOffset: end,
  111. truncated: end < buffer.length,
  112. };
  113. }