-
Notifications
You must be signed in to change notification settings - Fork 52
Expand file tree
/
Copy pathserver_job.lua
More file actions
328 lines (286 loc) · 10.6 KB
/
server_job.lua
File metadata and controls
328 lines (286 loc) · 10.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
local state = require('opencode.state')
local curl = require('opencode.curl')
local Promise = require('opencode.promise')
local opencode_server = require('opencode.opencode_server')
local port_mapping = require('opencode.port_mapping')
local log = require('opencode.log')
local config = require('opencode.config')
local util = require('opencode.util')
local M = {}
M.requests = {}
--- Wrapper for port_mapping.unregister to maintain backward compatibility
--- @param port number|nil
function M.unregister_port_usage(port)
port_mapping.unregister(port, state.opencode_server)
end
--- @param base_url string
--- @param timeout number
--- @return Promise<string|nil>
local function try_custom_server(base_url, timeout)
local promise = Promise.new()
local health_url = base_url .. '/global/health'
log.debug('try_custom_server: checking health at %s', health_url)
curl.request({
url = health_url,
method = 'GET',
timeout = timeout * 1000,
proxy = '', -- Disable proxy for health check
callback = function(response)
if response and response.status >= 200 and response.status < 300 then
local success, health_data = pcall(vim.json.decode, response.body)
if success and health_data then
log.debug('try_custom_server: health check passed')
promise:resolve(base_url)
return
end
end
local err_msg =
string.format('Health check failed at %s (status: %d)', health_url, response and response.status or 0)
log.debug('try_custom_server: %s', err_msg)
promise:reject(err_msg)
end,
on_error = function(err)
log.debug('try_custom_server: error connecting to %s: %s', health_url, vim.inspect(err))
promise:reject(err)
end,
})
return promise
end
--- @param response {status: integer, body: string}
--- @param cb fun(err: any, result: any)
local function handle_api_response(response, cb)
local success, json_body = pcall(vim.json.decode, response.body)
if response.status >= 200 and response.status < 300 then
cb(nil, success and json_body or response.body)
else
cb(success and json_body or response.body, nil)
end
end
--- Make an HTTP API call to the opencode server.
--- @generic T
--- @param url string The API endpoint URL
--- @param method string|nil HTTP method (default: 'GET')
--- @param body table|nil|boolean Request body (will be JSON encoded)
--- @return Promise<T> promise A promise that resolves with the result or rejects with an error
function M.call_api(url, method, body)
local call_promise = Promise.new()
state.jobs.increment_count()
local request_entry = { nil, call_promise }
table.insert(M.requests, request_entry)
local function remove_from_requests()
for i, entry in ipairs(M.requests) do
if entry == request_entry then
table.remove(M.requests, i)
break
end
end
state.jobs.set_count(#M.requests)
end
local opts = {
url = url,
method = method or 'GET',
headers = { ['Content-Type'] = 'application/json' },
proxy = '',
callback = function(response)
remove_from_requests()
handle_api_response(response, function(err, result)
if err then
local ok, pcall_err = pcall(function()
call_promise:reject(err)
end)
if not ok then
log.notify('Error while handling API error response: ' .. vim.inspect(pcall_err), vim.log.levels.ERROR)
end
else
local ok, pcall_err = pcall(function()
call_promise:resolve(result)
end)
if not ok then
log.notify('Error while handling API response: ' .. vim.inspect(pcall_err), vim.log.levels.ERROR)
end
end
end)
end,
on_error = function(err)
remove_from_requests()
local ok, pcall_err = pcall(function()
call_promise:reject(err)
end)
if not ok then
log.notify('Error while handling API on_error: ' .. vim.inspect(pcall_err), vim.log.levels.ERROR)
end
end,
}
if body ~= nil then
opts.body = body and vim.json.encode(body) or '{}'
end
request_entry[1] = opts
curl.request(opts)
return call_promise
end
--- Make a streaming HTTP API call to the opencode server.
--- @param url string The API endpoint URL
--- @param method string|nil HTTP method (default: 'GET')
--- @param body table|nil|boolean Request body (will be JSON encoded)
--- @param on_chunk fun(chunk: string) Callback invoked for each chunk of data received
--- @return table The underlying job instance
function M.stream_api(url, method, body, on_chunk)
local opts = {
url = url,
method = method or 'GET',
proxy = '',
stream = function(err, chunk)
on_chunk(chunk)
end,
on_error = function(err)
if err.message:match('exit_code=nil') then
return
end
log.notify('Error in streaming request: ' .. vim.inspect(err), vim.log.levels.ERROR)
end,
on_exit = function(code, signal)
if code ~= 0 then
log.notify('Streaming request exited with code ' .. tostring(code), vim.log.levels.WARN)
end
end,
}
if body ~= nil then
opts.body = body and vim.json.encode(body) or '{}'
end
return curl.request(opts) --[[@as table]]
end
--- @return number|nil port, or nil if we should spawn local instead
local function resolve_port()
local custom_port = config.server.port or 'auto'
if custom_port ~= 'auto' then
return custom_port
end
if not config.server.spawn_command then
return port_mapping.find_any_existing_port()
end
local existing = port_mapping.find_port_for_directory(vim.fn.getcwd())
return existing or math.random(1024, 65535)
end
--- Ensure the opencode server is running, starting it if necessary.
--- @return Promise<OpencodeServer>
function M.ensure_server()
local promise = Promise.new()
if state.opencode_server and state.opencode_server:is_running() then
return promise:resolve(state.opencode_server)
end
local custom_url = config.server.url
if not custom_url then
log.debug('ensure_server: server.url not configured, spawning local server')
M.spawn_local_server(promise)
return promise
end
local custom_port = resolve_port(custom_url)
if not custom_port then
M.spawn_local_server(promise)
return promise
end
local base_url = string.format('%s:%d', util.normalize_url_protocol(custom_url), custom_port)
local timeout = config.server.timeout or 5
log.debug('ensure_server: trying custom server at %s (timeout=%ds)', base_url, timeout)
M.try_connect_to_custom_server(base_url, timeout, promise, custom_port, custom_url)
return promise
end
local function retry_connect(base_url, timeout, max_retries, on_success, on_failure)
local function attempt(retry_count)
vim.defer_fn(function()
try_custom_server(base_url, timeout):and_then(on_success):catch(function(err)
if retry_count < max_retries then
attempt(retry_count + 1)
else
log.error('try_connect_to_custom_server: exhausted %d retries: %s', max_retries, vim.inspect(err))
on_failure(err)
end
end)
end, retry_count * (config.server.retry_delay or 2000))
end
attempt(1)
end
local function spawn_and_retry(base_url, custom_port, custom_url, promise, timeout)
local ok, result = pcall(config.server.spawn_command, custom_port, custom_url)
if not ok then
log.error('spawn_command failed: %s', vim.inspect(result))
promise:reject(string.format('Failed to spawn custom server on port %d', custom_port))
return
end
local server_pid = type(result) == 'number' and result or nil
retry_connect(base_url, timeout, 3, function(url)
port_mapping.register(custom_port, vim.fn.getcwd(), true, 'custom', url, server_pid)
state.jobs.set_server(opencode_server.from_custom(url, custom_port, 'custom'))
promise:resolve(state.opencode_server)
end, function(_err)
if config.server.port == 'auto' then
log.notify('Failed to connect after spawning, falling back to local server', vim.log.levels.WARN)
M.spawn_local_server(promise, custom_port, custom_url)
else
promise:reject(string.format('Failed to connect to custom server after spawning on port %d', custom_port))
end
end)
end
function M.try_connect_to_custom_server(base_url, timeout, promise, custom_port, custom_url)
try_custom_server(base_url, timeout)
:and_then(function(url)
local existing_started_by_nvim = port_mapping.started_by_nvim(custom_port)
local mode = config.server.spawn_command and 'custom' or 'attach'
port_mapping.register(custom_port, vim.fn.getcwd(), existing_started_by_nvim, mode, url, nil)
state.jobs.set_server(opencode_server.from_custom(url, custom_port, mode))
log.notify(
string.format('Connected to remote server at %s on port %d.', base_url, custom_port),
vim.log.levels.INFO
)
promise:resolve(state.opencode_server)
end)
:catch(function(err)
log.warn('failed to connect to %s: %s', base_url, vim.inspect(err))
if config.server.spawn_command and custom_port and custom_url then
spawn_and_retry(base_url, custom_port, custom_url, promise, timeout)
else
M.spawn_local_server(promise, custom_port, custom_url)
end
end)
end
--- @param promise Promise<OpencodeServer>
--- @param port? number|string Optional custom port
--- @param hostname? string Optional custom hostname
function M.spawn_local_server(promise, port, hostname)
state.jobs.set_server(opencode_server.new())
local spawn_opts = {
on_ready = function(job, base_url)
local url_port = base_url:match(':(%d+)')
log.notify(string.format('Started local server at %s', base_url), vim.log.levels.INFO)
if url_port then
local port_num = tonumber(url_port)
state.jobs.set_server_port(port_num)
local server_pid = job and job.pid
port_mapping.register(port_num, vim.fn.getcwd(), true, 'serve', nil, server_pid)
log.debug(
'spawn_local_server: registered port %d for reference counting (server_pid=%s)',
port_num,
tostring(server_pid)
)
end
promise:resolve(state.opencode_server)
end,
on_error = function(err)
log.notify(' Failed to start opencode server' .. vim.inspect(err), vim.log.levels.ERROR)
promise:reject(err)
end,
on_exit = function(exit_opts)
promise:reject('Server exited')
end,
}
if port then
spawn_opts.port = port
end
if hostname then
hostname = hostname:gsub('^%a[%w+%.%-]*://', '')
hostname = hostname:match('^[^/]+') or hostname
spawn_opts.hostname = hostname
end
state.opencode_server:spawn(spawn_opts)
end
return M