MCPcopy Create free account
hub / github.com/SplootCode/splootcode / syncFetch

Function syncFetch

packages/runtime-python/src/webworker.ts:110–168  ·  view source on GitHub ↗
(method: string, url: string, headers: any, body: any)

Source from the content-addressed store, hash-verified

108}
109
110const syncFetch = (method: string, url: string, headers: any, body: any): ResponseData => {
111 let objHeaders = {}
112 let bodyArray: Uint8Array | string = null
113 if (pyodide.isPyProxy(headers) && headers.type === 'dict') {
114 objHeaders = headers.toJs({ dict_converter: Object.fromEntries })
115 }
116 if (typeof body === 'string') {
117 bodyArray = body
118 } else if (pyodide.isPyProxy(body) && body.type === 'bytes') {
119 bodyArray = body.toJs() as Uint8Array
120 }
121
122 if (rerun) {
123 return replayFetch({ method, url, headers: objHeaders, body: bodyArray })
124 }
125
126 sendMessage({
127 type: 'fetch',
128 data: {
129 method: method,
130 url: url,
131 headers: objHeaders,
132 body: bodyArray,
133 },
134 })
135 const res = Atomics.wait(fetchBufferMeta, 0, 0)
136 if (res === 'timed-out') {
137 // TODO: Support request timeout
138 }
139 const headerSize = Atomics.exchange(fetchBufferMeta, 1, 0)
140 const bodySize = Atomics.exchange(fetchBufferMeta, 2, 0)
141 const totalSize = headerSize + bodySize
142 let buffer: Uint8Array
143 if (totalSize <= fetchBuffer.length) {
144 buffer = fetchBuffer
145 Atomics.store(fetchBufferMeta, 0, 0)
146 } else {
147 let bytesRead = 0
148 buffer = new Uint8Array(totalSize)
149 while (bytesRead < totalSize) {
150 const toRead = Math.min(totalSize - bytesRead, fetchBuffer.length)
151 buffer.set(fetchBuffer.subarray(0, toRead), bytesRead)
152 bytesRead += toRead
153 Atomics.store(fetchBufferMeta, 0, 0)
154 if (bytesRead < totalSize) {
155 sendMessage({ type: 'continueFetch' })
156 Atomics.wait(fetchBufferMeta, 0, 0)
157 }
158 }
159 }
160 const bytes = buffer.slice(0, headerSize)
161 const contentBytes = buffer.slice(headerSize, headerSize + bodySize)
162
163 const decoder = new TextDecoder()
164 const textJSON = decoder.decode(bytes)
165 const result = JSON.parse(textJSON) as ResponseData
166 result.body = contentBytes
167 return result

Callers

nothing calls this directly

Calls 2

replayFetchFunction · 0.85
sendMessageFunction · 0.70

Tested by

no test coverage detected