Repository navigation
Expand file tree
/
Copy pathclient_engine.go
More file actions
334 lines (302 loc) · 12.3 KB
/
Copy pathclient_engine.go
File metadata and controls
334 lines (302 loc) · 12.3 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
329
330
331
332
333
334
// Copyright The Pit Project Owners. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Please see https://openpit.dev and the OWNERS file for details.
package openpit
import (
"errors"
"runtime"
"runtime/cgo"
"sync"
"go.openpit.dev/openpit/accountadjustment"
"go.openpit.dev/openpit/accounts"
"go.openpit.dev/openpit/configure"
"go.openpit.dev/openpit/internal/callback"
"go.openpit.dev/openpit/internal/native"
"go.openpit.dev/openpit/model"
"go.openpit.dev/openpit/param"
"go.openpit.dev/openpit/pretrade"
"go.openpit.dev/openpit/reject"
)
// ErrClientRequestClosed is returned by ClientRequest.Execute and
// ClientRequest.Reviews after Close.
var ErrClientRequestClosed = errors.New("client pre-trade request already closed")
// ClientEngineOption configures a ClientEngine at build time.
type ClientEngineOption func(*clientEngineOptions)
// UnsafeFastClientPayloadCallbacks selects callback adapters that trust every
// client payload reaching client policies to carry the builder's declared type.
//
// This mode removes safe adapter checks from every callback. A missing payload
// or a wrong payload type panics inside the adapter; the SDK callback boundary
// recovers it as a SystemUnavailable policy failure.
func UnsafeFastClientPayloadCallbacks() ClientEngineOption {
return func(options *clientEngineOptions) {
options.unsafeFastPayloadCallbacks = true
}
}
type clientEngineOptions struct {
unsafeFastPayloadCallbacks bool
}
type clientAccountAdjustment interface {
EngineAccountAdjustment() model.AccountAdjustment
}
// ClientEngine runs the standard engine through client-owned order, execution
// report, and account-adjustment types.
//
// The ordinary Engine API remains the zero-payload fast path. ClientEngine is
// the opt-in path that allocates a cgo.Handle per submitted client payload so
// callbacks can receive the original typed value.
//
// Threading: ClientEngine follows the same threading contract as Engine.
// Payload handles allocated by the SDK (cgo.Handle wrapped around the client
// value) are released synchronously inside the same call that created them, so
// callers do not need to extend payload lifetime beyond that call.
type ClientEngine[
Order pretrade.ClientOrder,
Report pretrade.ClientExecutionReport,
Adjustment clientAccountAdjustment,
] struct {
engine *Engine
}
// Stop releases the underlying engine.
func (e *ClientEngine[Order, Report, Adjustment]) Stop() {
e.engine.Stop()
}
// StartPreTrade runs the start stage with a client order payload.
//
// On accept, the returned ClientRequest owns the payload handle and releases it
// when Execute or Close is called. On reject or error, the handle is released
// before StartPreTrade returns.
// If the request's Reviews() returns marks, obtain a human decision before
// sending the order.
func (e *ClientEngine[Order, Report, Adjustment]) StartPreTrade(
order Order,
) (*ClientRequest, []reject.Reject, error) {
engineOrder, payload, sourceOrder := newClientOrderPayload(order)
request, rejects, err := e.engine.StartPreTrade(engineOrder)
runtime.KeepAlive(sourceOrder)
runtime.KeepAlive(order)
if err != nil || rejects != nil {
payload.release()
return nil, rejects, err
}
return newClientRequest(request, payload), nil, nil
}
// ExecutePreTrade runs the full pre-trade pipeline with a client order payload.
//
// The payload handle is released before ExecutePreTrade returns because all
// order callbacks have completed by then.
// If the reservation's Reviews() returns marks, obtain a human decision
// before sending the order.
func (e *ClientEngine[Order, Report, Adjustment]) ExecutePreTrade(
order Order,
) (*pretrade.Reservation, []reject.Reject, error) {
engineOrder, payload, sourceOrder := newClientOrderPayload(order)
defer payload.release()
reservation, rejects, err := e.engine.ExecutePreTrade(engineOrder)
runtime.KeepAlive(sourceOrder)
runtime.KeepAlive(order)
return reservation, rejects, err
}
// ApplyDropCopy applies the full non-enforcing pre-trade pipeline with a client
// order payload. The payload handle is released before ApplyDropCopy returns
// because all order callbacks have completed by then.
func (e *ClientEngine[Order, Report, Adjustment]) ApplyDropCopy(
order Order,
) (*pretrade.DropCopyOperation, []reject.Reject, error) {
engineOrder, payload, sourceOrder := newClientOrderPayload(order)
defer payload.release()
operation, rejects, err := e.engine.ApplyDropCopy(engineOrder)
runtime.KeepAlive(sourceOrder)
runtime.KeepAlive(order)
return operation, rejects, err
}
// ApplyExecutionReport applies a client execution report payload.
//
// The payload handle is released before ApplyExecutionReport returns because
// report callbacks are synchronous.
func (e *ClientEngine[Order, Report, Adjustment]) ApplyExecutionReport(
report Report,
) (PostTradeResult, error) {
engineReport, payload, sourceReport := newClientReportPayload(report)
defer payload.release()
result, err := e.engine.ApplyExecutionReport(engineReport)
runtime.KeepAlive(sourceReport)
runtime.KeepAlive(report)
return result, err
}
// ApplyAccountAdjustment applies client account-adjustment payloads.
//
// Payload handles are released before ApplyAccountAdjustment returns because
// account-adjustment callbacks are synchronous.
func (e *ClientEngine[Order, Report, Adjustment]) ApplyAccountAdjustment(
accountID param.AccountID,
adjustments []Adjustment,
) (accountadjustment.BatchResult, error) {
engineAdjustments, payloads, sourceAdjustments := newClientAdjustmentPayloads(adjustments)
defer payloads.release()
result, err := e.engine.ApplyAccountAdjustment(accountID, engineAdjustments)
runtime.KeepAlive(sourceAdjustments)
runtime.KeepAlive(adjustments)
return result, err
}
// RetireAccount forgets zero, unused state for accountID. It follows the
// same caller contract and returns the same errors as Engine.RetireAccount.
func (e *ClientEngine[Order, Report, Adjustment]) RetireAccount(accountID param.AccountID) error {
return e.engine.RetireAccount(accountID)
}
// Accounts returns an accessor for account-group management bound to this
// engine. Account-group membership is keyed by account id and is independent of
// the client payload types, so the accessor is the same one the standard Engine
// exposes.
func (e *ClientEngine[Order, Report, Adjustment]) Accounts() accounts.Accounts {
return e.engine.Accounts()
}
// Configure returns an accessor for runtime policy-settings updates bound to
// this engine. Policy configuration is independent of the client payload types,
// so the accessor is the same one the standard Engine exposes.
func (e *ClientEngine[Order, Report, Adjustment]) Configure() configure.Configurator {
return e.engine.Configure()
}
// ClientRequest is a deferred pre-trade request that keeps the original client
// order payload alive until the request is executed or closed.
//
// Lifecycle: the caller owns the request and must release it with Close.
// Nothing releases it on the caller's behalf - there is no finalizer, so a
// request dropped without Close leaks its native handle and the client order
// payload it keeps alive.
//
// Concurrency: every method is safe to call concurrently with every other
// method on the same value, including Close.
type ClientRequest struct {
mu sync.Mutex
request *pretrade.Request
payload *clientPayloadHandle
}
func newClientRequest(request *pretrade.Request, payload *clientPayloadHandle) *ClientRequest {
return &ClientRequest{request: request, payload: payload}
}
// Close releases the request and the client order payload.
//
// Idempotency: safe to call more than once; subsequent calls are no-ops.
func (r *ClientRequest) Close() {
r.mu.Lock()
defer r.mu.Unlock()
if r.request != nil {
r.request.Close()
r.request = nil
}
r.payload.release()
}
// Reviews returns a copy of the start-stage review marks. A non-empty list
// requires a human decision before sending the order.
// If Execute returns a hold for review, commit the reservation to retain the
// hold and keep the order unsent. On approval, rerun with Confirmed and add
// AlreadyHeld only if Spot Funds kept its own hold in the committed review.
//
// See [pretrade.Reservation] for the lifecycle.
//
// After Execute, read the marks from the returned reservation. Reviews returns
// the native error after Execute and ErrClientRequestClosed after Close.
func (r *ClientRequest) Reviews() ([]reject.Reject, error) {
r.mu.Lock()
defer r.mu.Unlock()
if r.request == nil {
return nil, ErrClientRequestClosed
}
return r.request.Reviews()
}
// Execute runs the deferred pre-trade request and releases the client order
// payload after callbacks complete.
// If the reservation's Reviews() returns marks, obtain a human decision
// before sending the order.
//
// Execute does not close the underlying request; call Close after Execute just
// as with a standard pretrade.Request.
//
// A call after Close returns [ErrClientRequestClosed]. Native execution
// failures remain distinguishable through the returned error value.
func (r *ClientRequest) Execute() (*pretrade.Reservation, []reject.Reject, error) {
// Execute consumes the native request, so it takes the exclusive lock: a
// concurrent Close must not release the handle mid-call.
r.mu.Lock()
defer r.mu.Unlock()
if r.request == nil {
return nil, nil, ErrClientRequestClosed
}
reservation, rejects, err := r.request.Execute()
r.payload.release()
return reservation, rejects, err
}
type clientPayloadHandle struct {
handle cgo.Handle
once sync.Once
}
func newClientPayloadHandle(value any) *clientPayloadHandle {
return &clientPayloadHandle{handle: cgo.NewHandle(value)}
}
func (h *clientPayloadHandle) release() {
if h == nil {
return
}
h.once.Do(func() { h.handle.Delete() })
}
type clientPayloadHandles []*clientPayloadHandle
func (handles clientPayloadHandles) release() {
for _, payload := range handles {
payload.release()
}
}
func newClientOrderPayload[Order pretrade.ClientOrder](
order Order,
) (model.Order, *clientPayloadHandle, model.Order) {
engineOrder := order.EngineOrder()
nativeOrder := engineOrder.Handle()
payload := newClientPayloadHandle(order)
native.OrderSetUserData(&nativeOrder, callback.NewUserDataFromHandle(payload.handle))
return model.NewOrderFromHandle(nativeOrder), payload, engineOrder
}
func newClientReportPayload[Report pretrade.ClientExecutionReport](
report Report,
) (model.ExecutionReport, *clientPayloadHandle, model.ExecutionReport) {
engineReport := report.EngineExecutionReport()
nativeReport := engineReport.Handle()
payload := newClientPayloadHandle(report)
native.ExecutionReportSetUserData(&nativeReport, callback.NewUserDataFromHandle(payload.handle))
return model.NewExecutionReportFromHandle(nativeReport), payload, engineReport
}
func newClientAdjustmentPayloads[Adjustment clientAccountAdjustment](
adjustments []Adjustment,
) ([]model.AccountAdjustment, clientPayloadHandles, []model.AccountAdjustment) {
engineAdjustments := make([]model.AccountAdjustment, len(adjustments))
payloads := make(clientPayloadHandles, len(adjustments))
sourceAdjustments := make([]model.AccountAdjustment, len(adjustments))
for i, adjustment := range adjustments {
engineAdjustments[i], payloads[i], sourceAdjustments[i] = newClientAdjustmentPayload(adjustment)
}
return engineAdjustments, payloads, sourceAdjustments
}
func newClientAdjustmentPayload[Adjustment clientAccountAdjustment](
adjustment Adjustment,
) (model.AccountAdjustment, *clientPayloadHandle, model.AccountAdjustment) {
engineAdjustment := adjustment.EngineAccountAdjustment()
nativeAdjustment := engineAdjustment.Handle()
payload := newClientPayloadHandle(adjustment)
native.AccountAdjustmentSetUserData(
&nativeAdjustment,
callback.NewUserDataFromHandle(payload.handle),
)
return model.NewAccountAdjustmentFromHandle(nativeAdjustment), payload, engineAdjustment
}