|
| 1 | +import * as Clock from 'effect/Clock' |
| 2 | +import * as DateTime from 'effect/DateTime' |
| 3 | +import * as Effect from 'effect/Effect' |
| 4 | +import * as Option from 'effect/Option' |
| 5 | +import * as Schema from 'effect/Schema' |
| 6 | + |
| 7 | +import type { ThreadId } from '../../core/Identifiers' |
| 8 | +import { IdempotencyKey } from '../../core/Receipt' |
| 9 | +import type { HostUpdateRequest } from '../HostUpdates' |
| 10 | +import { HostUpdateAppended, HostUpdateError } from '../HostUpdates.schema' |
| 11 | +import { |
| 12 | + BatchId, |
| 13 | + CanonicalBatch, |
| 14 | + type CanonicalRecordEnvelope, |
| 15 | + type DeploymentId, |
| 16 | + PersistedJson, |
| 17 | + type ProducerId, |
| 18 | + RecordEnvelope, |
| 19 | + RecordId, |
| 20 | + ThreadHostUpdateAppended, |
| 21 | +} from '../Records' |
| 22 | +import { |
| 23 | + type AppendConflict, |
| 24 | + AppendRequest, |
| 25 | + getRecord, |
| 26 | + ThreadReader, |
| 27 | + ThreadStore, |
| 28 | + type ThreadStoreFailure, |
| 29 | + ThreadTailRequest, |
| 30 | +} from '../ThreadStore' |
| 31 | +import { WakeScheduler } from '../WakeScheduler' |
| 32 | + |
| 33 | +const MAX_TAIL_RETRIES = 8 |
| 34 | + |
| 35 | +const invalid = () => HostUpdateError.make({ reason: 'validation', message: 'The host update is not bounded JSON' }) |
| 36 | + |
| 37 | +const conflicting = () => |
| 38 | + HostUpdateError.make({ reason: 'conflict', message: 'The update ID was already used with a different update' }) |
| 39 | + |
| 40 | +const contended = () => |
| 41 | + HostUpdateError.make({ reason: 'contention', message: 'The Thread tail kept moving; the update did not commit' }) |
| 42 | + |
| 43 | +const decodeRecord = Schema.decodeUnknownEffect( |
| 44 | + Schema.Struct({ |
| 45 | + updateId: IdempotencyKey, |
| 46 | + update: PersistedJson, |
| 47 | + relatedRunId: Schema.optionalKey(ThreadHostUpdateAppended.fields.relatedRunId), |
| 48 | + }), |
| 49 | +) |
| 50 | + |
| 51 | +const isHostUpdate = Schema.is(ThreadHostUpdateAppended) |
| 52 | + |
| 53 | +const recordIdOf = (updateId: IdempotencyKey) => RecordId.make(`host-update:${updateId}`) |
| 54 | +const batchIdOf = (updateId: IdempotencyKey) => BatchId.make(`host-update:${updateId}`) |
| 55 | + |
| 56 | +const matches = (existing: CanonicalRecordEnvelope, payload: ThreadHostUpdateAppended) => |
| 57 | + isHostUpdate(existing.record.payload) && |
| 58 | + Schema.toEquivalence(ThreadHostUpdateAppended)(existing.record.payload, payload) |
| 59 | + |
| 60 | +const actualTailOf = (conflict: AppendConflict) => |
| 61 | + Option.fromUndefinedOr(conflict.actualTailSequence).pipe(Option.filter(() => conflict.reason === 'tail')) |
| 62 | + |
| 63 | +/** @internal Appends host-authored Thread updates under the same progress gate as Run writes. */ |
| 64 | +export const makeHostUpdateRuntime = Effect.fnUntraced(function*(options: { |
| 65 | + readonly deploymentId: DeploymentId |
| 66 | + readonly producerId: ProducerId |
| 67 | +}) { |
| 68 | + const store = yield* ThreadStore |
| 69 | + const wake = yield* WakeScheduler |
| 70 | + const reader = ThreadReader.fromStore(store) |
| 71 | + |
| 72 | + const existing = (threadId: ThreadId, payload: ThreadHostUpdateAppended) => |
| 73 | + getRecord({ threadId, recordId: recordIdOf(payload.updateId) }).pipe( |
| 74 | + Effect.provideService(ThreadReader, reader), |
| 75 | + Effect.flatMap(Option.match({ |
| 76 | + onNone: () => Effect.fail(conflicting()), |
| 77 | + onSome: (found) => |
| 78 | + matches(found, payload) |
| 79 | + ? Effect.succeed(HostUpdateAppended.make({ sequence: found.sequence, deduplicated: true })) |
| 80 | + : Effect.fail(conflicting()), |
| 81 | + })), |
| 82 | + ) |
| 83 | + |
| 84 | + const commit = (threadId: ThreadId, batch: CanonicalBatch, payload: ThreadHostUpdateAppended) => { |
| 85 | + const attempt = (expectedTailSequence: CanonicalRecordEnvelope['sequence'], retries: number): Effect.Effect< |
| 86 | + HostUpdateAppended, |
| 87 | + HostUpdateError | ThreadStoreFailure |
| 88 | + > => |
| 89 | + store.append(AppendRequest.make({ threadId, batch, expectedTailSequence })).pipe( |
| 90 | + Effect.map((result) => |
| 91 | + HostUpdateAppended.make({ sequence: result.firstSequence, deduplicated: result.replayed }) |
| 92 | + ), |
| 93 | + Effect.catchTag('AppendConflict', (conflict) => |
| 94 | + Option.match(actualTailOf(conflict), { |
| 95 | + onNone: () => existing(threadId, payload), |
| 96 | + onSome: (tail) => retryAfter(tail, retries), |
| 97 | + })), |
| 98 | + ) |
| 99 | + |
| 100 | + const retryAfter = (tail: CanonicalRecordEnvelope['sequence'], retries: number) => |
| 101 | + retries >= MAX_TAIL_RETRIES ? Effect.fail(contended()) : attempt(tail, retries + 1) |
| 102 | + |
| 103 | + return store.inspectTail(ThreadTailRequest.make({ threadId })).pipe( |
| 104 | + Effect.flatMap((tail) => attempt(tail.tailSequence, 0)), |
| 105 | + ) |
| 106 | + } |
| 107 | + |
| 108 | + const append = Effect.fnUntraced(function*(request: HostUpdateRequest) { |
| 109 | + const fields = yield* decodeRecord({ |
| 110 | + updateId: request.updateId, |
| 111 | + update: request.update, |
| 112 | + ...(request.relatedRunId === undefined ? {} : { relatedRunId: request.relatedRunId }), |
| 113 | + }).pipe(Effect.mapError(invalid)) |
| 114 | + const payload = ThreadHostUpdateAppended.make(fields) |
| 115 | + const createdAt = DateTime.makeUnsafe(yield* Clock.currentTimeMillis) |
| 116 | + const batch = CanonicalBatch.make({ |
| 117 | + batchId: batchIdOf(payload.updateId), |
| 118 | + producerId: options.producerId, |
| 119 | + records: [ |
| 120 | + RecordEnvelope.make({ |
| 121 | + recordId: recordIdOf(payload.updateId), |
| 122 | + family: 'thread', |
| 123 | + schemaVersion: 1, |
| 124 | + createdAt, |
| 125 | + deploymentId: options.deploymentId, |
| 126 | + payload, |
| 127 | + }), |
| 128 | + ], |
| 129 | + }) |
| 130 | + const appended = yield* commit(request.threadId, batch, payload) |
| 131 | + |
| 132 | + yield* wake.notify(request.threadId, 'progress') |
| 133 | + |
| 134 | + return appended |
| 135 | + }) |
| 136 | + |
| 137 | + return { append } |
| 138 | +}) |
0 commit comments