share.ts 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. import { FileDiff, Message, Model, Part, Session } from "@opencode-ai/sdk/v2"
  2. import { fn } from "@opencode-ai/util/fn"
  3. import { iife } from "@opencode-ai/util/iife"
  4. import z from "zod"
  5. import { Storage } from "./storage"
  6. export namespace Share {
  7. export const Info = z.object({
  8. id: z.string(),
  9. secret: z.string(),
  10. sessionID: z.string(),
  11. })
  12. export type Info = z.infer<typeof Info>
  13. export const Data = z.discriminatedUnion("type", [
  14. z.object({
  15. type: z.literal("session"),
  16. data: z.custom<Session>(),
  17. }),
  18. z.object({
  19. type: z.literal("message"),
  20. data: z.custom<Message>(),
  21. }),
  22. z.object({
  23. type: z.literal("part"),
  24. data: z.custom<Part>(),
  25. }),
  26. z.object({
  27. type: z.literal("session_diff"),
  28. data: z.custom<FileDiff[]>(),
  29. }),
  30. z.object({
  31. type: z.literal("model"),
  32. data: z.custom<Model[]>(),
  33. }),
  34. ])
  35. export type Data = z.infer<typeof Data>
  36. type Snapshot = {
  37. data: Data[]
  38. }
  39. type Compaction = {
  40. event?: string
  41. data: Data[]
  42. }
  43. function key(item: Data) {
  44. switch (item.type) {
  45. case "session":
  46. return "session"
  47. case "message":
  48. return `message/${item.data.id}`
  49. case "part":
  50. return `part/${item.data.messageID}/${item.data.id}`
  51. case "session_diff":
  52. return "session_diff"
  53. case "model":
  54. return "model"
  55. }
  56. }
  57. function merge(...items: Data[][]) {
  58. const map = new Map<string, Data>()
  59. for (const list of items) {
  60. for (const item of list) {
  61. map.set(key(item), item)
  62. }
  63. }
  64. return Array.from(map.entries())
  65. .sort(([a], [b]) => a.localeCompare(b))
  66. .map(([, item]) => item)
  67. }
  68. async function readSnapshot(shareID: string) {
  69. return (await Storage.read<Snapshot>(["share_snapshot", shareID]))?.data
  70. }
  71. async function writeSnapshot(shareID: string, data: Data[]) {
  72. await Storage.write<Snapshot>(["share_snapshot", shareID], { data })
  73. }
  74. async function legacy(shareID: string) {
  75. const compaction: Compaction = (await Storage.read<Compaction>(["share_compaction", shareID])) ?? {
  76. data: [],
  77. event: undefined,
  78. }
  79. const list = await Storage.list({
  80. prefix: ["share_event", shareID],
  81. before: compaction.event,
  82. }).then((x) => x.toReversed())
  83. if (list.length === 0) {
  84. if (compaction.data.length > 0) await writeSnapshot(shareID, compaction.data)
  85. return compaction.data
  86. }
  87. const next = merge(
  88. compaction.data,
  89. await Promise.all(list.map(async (event) => await Storage.read<Data[]>(event))).then((x) =>
  90. x.flatMap((item) => item ?? []),
  91. ),
  92. )
  93. await Promise.all([
  94. Storage.write(["share_compaction", shareID], {
  95. event: list.at(-1)?.at(-1),
  96. data: next,
  97. }),
  98. writeSnapshot(shareID, next),
  99. ])
  100. return next
  101. }
  102. export const create = fn(z.object({ sessionID: z.string() }), async (body) => {
  103. const isTest = process.env.NODE_ENV === "test" || body.sessionID.startsWith("test_")
  104. const info: Info = {
  105. id: (isTest ? "test_" : "") + body.sessionID.slice(-8),
  106. sessionID: body.sessionID,
  107. secret: crypto.randomUUID(),
  108. }
  109. const exists = await get(info.id)
  110. if (exists) throw new Errors.AlreadyExists(info.id)
  111. await Promise.all([Storage.write(["share", info.id], info), writeSnapshot(info.id, [])])
  112. return info
  113. })
  114. export async function get(id: string) {
  115. return Storage.read<Info>(["share", id])
  116. }
  117. export const remove = fn(Info.pick({ id: true, secret: true }), async (body) => {
  118. const share = await get(body.id)
  119. if (!share) throw new Errors.NotFound(body.id)
  120. if (share.secret !== body.secret) throw new Errors.InvalidSecret(body.id)
  121. await Storage.remove(["share", body.id])
  122. const groups = await Promise.all([
  123. Storage.list({ prefix: ["share_snapshot", body.id] }),
  124. Storage.list({ prefix: ["share_compaction", body.id] }),
  125. Storage.list({ prefix: ["share_event", body.id] }),
  126. Storage.list({ prefix: ["share_data", body.id] }),
  127. ])
  128. for (const item of groups.flat()) {
  129. await Storage.remove(item)
  130. }
  131. })
  132. export const sync = fn(
  133. z.object({
  134. share: Info.pick({ id: true, secret: true }),
  135. data: Data.array(),
  136. }),
  137. async (input) => {
  138. const share = await get(input.share.id)
  139. if (!share) throw new Errors.NotFound(input.share.id)
  140. if (share.secret !== input.share.secret) throw new Errors.InvalidSecret(input.share.id)
  141. const data = (await readSnapshot(input.share.id)) ?? (await legacy(input.share.id))
  142. await writeSnapshot(input.share.id, merge(data, input.data))
  143. },
  144. )
  145. export async function data(shareID: string) {
  146. return (await readSnapshot(shareID)) ?? legacy(shareID)
  147. }
  148. export const syncOld = fn(
  149. z.object({
  150. share: Info.pick({ id: true, secret: true }),
  151. data: Data.array(),
  152. }),
  153. async (input) => {
  154. const share = await get(input.share.id)
  155. if (!share) throw new Errors.NotFound(input.share.id)
  156. if (share.secret !== input.share.secret) throw new Errors.InvalidSecret(input.share.id)
  157. const promises = []
  158. for (const item of input.data) {
  159. promises.push(
  160. iife(async () => {
  161. switch (item.type) {
  162. case "session":
  163. await Storage.write(["share_data", input.share.id, "session"], item.data)
  164. break
  165. case "message": {
  166. const data = item.data as Message
  167. await Storage.write(["share_data", input.share.id, "message", data.id], item.data)
  168. break
  169. }
  170. case "part": {
  171. const data = item.data as Part
  172. await Storage.write(["share_data", input.share.id, "part", data.messageID, data.id], item.data)
  173. break
  174. }
  175. case "session_diff":
  176. await Storage.write(["share_data", input.share.id, "session_diff"], item.data)
  177. break
  178. case "model":
  179. await Storage.write(["share_data", input.share.id, "model"], item.data)
  180. break
  181. }
  182. }),
  183. )
  184. }
  185. await Promise.all(promises)
  186. },
  187. )
  188. export const Errors = {
  189. NotFound: class extends Error {
  190. constructor(public id: string) {
  191. super(`Share not found: ${id}`)
  192. }
  193. },
  194. InvalidSecret: class extends Error {
  195. constructor(public id: string) {
  196. super(`Share secret invalid: ${id}`)
  197. }
  198. },
  199. AlreadyExists: class extends Error {
  200. constructor(public id: string) {
  201. super(`Share already exists: ${id}`)
  202. }
  203. },
  204. }
  205. }