-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbatch.go
More file actions
717 lines (667 loc) · 25 KB
/
Copy pathbatch.go
File metadata and controls
717 lines (667 loc) · 25 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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
package b24gosdk
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"sort"
"strconv"
"strings"
"github.com/bitrix24/b24gosdk/internal/phpq"
"github.com/bitrix24/b24gosdk/internal/rest"
)
// MaxBatchCommands is the number of commands the server executes in one batch.
//
// The limit is not left to the server to enforce: it answers an over-long batch
// with a per-command ERROR_BATCH_LENGTH_EXCEEDED for each surplus command, so
// the batch comes back looking like a partial success instead of a rejected
// call.
const MaxBatchCommands = 50
const batchMethod = "batch"
// ErrBatchLengthExceeded is returned when a batch holds more than
// MaxBatchCommands commands. Split it with Chunks, or use CallBatchChunked.
var ErrBatchLengthExceeded = errors.New("b24gosdk: batch is longer than the server accepts")
// ErrBadRef is returned by Ref for an id or path segment the server cannot read
// back. Every Ref error wraps it.
var ErrBadRef = errors.New("b24gosdk: bad $result reference")
// ErrV3BatchUnsupported is returned by CallBatch and CallBatchChunked when the
// client addresses REST 3.0.
//
// REST 3.0 has a batch method, but not this batch: it takes each command as
// {"method": …, "query": {…}} at the top level of the body, answers with a plain
// ARRAY in submission order — the command ids are discarded — and aborts the
// whole request on the first failing command instead of reporting per-command
// errors in result_error. So Batch, Ref, Halt and BatchResult, which are the
// v1 protocol, have nothing to map onto, and the "partial failure" that
// BatchError exists for does not occur.
//
// The refusal replaces the portal's own answer to a v1 batch body, which is
// BITRIX_REST_V3_EXCEPTION_INVALIDSELECTEXCEPTION, "Не удается распознать
// выражение select" — a message about `select`, for a request that has none.
//
// Until the SDK speaks the v3 format, send it through Core.Call:
//
// res, err := client.Core().Call(ctx, "batch", b24gosdk.Params{
// "cnt": b24gosdk.Params{"method": "humanresources.employee.count", "query": b24gosdk.Params{}},
// })
// // res.Result is [{"total":19}] — an array, positional
var ErrV3BatchUnsupported = errors.New("b24gosdk: Batch works with REST v1 only; REST 3.0 batch takes method/query commands and answers with a positional array — call it through Core.Call")
// CmdID identifies one command inside a batch. It is the key the results come
// back under and the name a $result placeholder refers to.
type CmdID string
// Cmd is one command of a batch.
type Cmd struct {
ID CmdID
Method string
Params any
}
// Batch is a set of REST calls executed by the server in one request.
//
// One batch costs ONE token of the FREQUENCY limit instead of one per command,
// which is the whole reason it exists: fifty creates through Call spend fifty
// tokens and take fifty round trips.
//
// # What it does not save
//
// The work. The portal still runs all fifty commands, one after another, and
// still charges their execution time against the RESOURCE-INTENSITY limit
// (the `operating` seconds in a response's time block). That counter is kept per
// method, and a batch is charged on its own — so watching crm.deal.add's
// counter after a batch of fifty adds shows almost nothing, and the cost is
// nonetheless there. Batching many writes moves the pressure from one limit to
// the other; it does not remove it.
//
// # How long it takes
//
// As long as the sum. The commands run sequentially inside ONE HTTP request:
// 50 crm.deal.add measured at 28-32 seconds on a live portal, roughly 0.6s each,
// with the first command finishing half a minute before the last.
//
// That is longer than most default timeouts, and the failure it produces is the
// expensive kind. An http.Client{Timeout: 30 * time.Second} cuts the connection
// AFTER the portal has already created part of the deals, which is an ambiguous
// failure — the SDK does not replay it, because replaying would create them
// twice — and the identifiers of everything that WAS created go with it.
//
// So bound a batch of writes by what it will actually take: the ctx passed to
// CallBatch, and an http.Client timeout above the expected total (the SDK's
// default client has none, which is why this bites only those who set one).
//
// Commands run in submission order, so a later command can reference an earlier
// one's result through Ref.
type Batch struct {
// Halt stops the batch at the first command that fails.
//
// A CHAINED batch — one where a later command references an earlier result
// through Ref — SHOULD set it. When a producer fails, its $result
// placeholder is not an error: the server substitutes the unresolved text as
// a LITERAL value, and the consumer runs with a corrupted parameter instead
// of not running at all.
Halt bool
cmds []Cmd
seen map[CmdID]bool
auto int
}
// NewBatch returns an empty batch.
func NewBatch() *Batch { return &Batch{seen: map[CmdID]bool{}} }
// Add appends a command and returns the generated id to reference it by.
//
// params may be nil for a method that takes none.
func (b *Batch) Add(method string, params any) (CmdID, error) {
b.auto++
id := CmdID("cmd" + strconv.Itoa(b.auto))
if err := b.AddAs(id, method, params); err != nil {
return "", err
}
return id, nil
}
// AddAs appends a command under an id you choose, which is what a readable
// $result chain wants: Ref("user", "ID") beats Ref("cmd1", "ID").
func (b *Batch) AddAs(id CmdID, method string, params any) error {
if b.seen == nil {
b.seen = map[CmdID]bool{}
}
if id == "" {
return errors.New("b24gosdk: batch: empty command id")
}
if b.seen[id] {
// The server would keep only the last one, silently dropping a command
// the caller believes it sent.
return fmt.Errorf("b24gosdk: batch: duplicate command id %q", id)
}
if err := checkRefPart(string(id), "command id"); err != nil {
return err
}
if strings.TrimSpace(method) == "" {
return errors.New("b24gosdk: batch: empty method name")
}
b.seen[id] = true
b.cmds = append(b.cmds, Cmd{ID: id, Method: method, Params: params})
return nil
}
// Len reports how many commands the batch holds.
func (b *Batch) Len() int { return len(b.cmds) }
// Cmds returns the commands in submission order.
func (b *Batch) Cmds() []Cmd { return append([]Cmd(nil), b.cmds...) }
// Chunks splits the batch into pieces the server accepts.
//
// It is for INDEPENDENT commands only. A $result reference cannot cross a chunk
// boundary — each chunk is a separate request with its own result namespace — so
// splitting a chained batch produces placeholders that resolve to nothing.
func (b *Batch) Chunks() []*Batch {
if len(b.cmds) <= MaxBatchCommands {
return []*Batch{b}
}
var out []*Batch
for i := 0; i < len(b.cmds); i += MaxBatchCommands {
end := min(i+MaxBatchCommands, len(b.cmds))
c := NewBatch()
c.Halt = b.Halt
for _, cmd := range b.cmds[i:end] {
c.seen[cmd.ID] = true
c.cmds = append(c.cmds, cmd)
}
out = append(out, c)
}
return out
}
// params renders the batch as the `batch` call's parameters.
func (b *Batch) params() (map[string]any, error) {
cmd := make(cmdMap, 0, len(b.cmds))
for _, c := range b.cmds {
m, err := paramsAsMap(c.Params)
if err != nil {
return nil, fmt.Errorf("b24gosdk: batch: command %q (%s): %w", c.ID, c.Method, err)
}
q, err := phpq.Encode(m)
if err != nil {
return nil, fmt.Errorf("b24gosdk: batch: command %q (%s): %w", c.ID, c.Method, err)
}
// "user.current?" — the separator is unconditional, exactly as CRest
// emits it; parse_str reads an empty query as no params.
cmd = append(cmd, cmdEntry{ID: c.ID, Call: c.Method + "?" + q})
}
return map[string]any{"halt": b.Halt, "cmd": cmd}, nil
}
// cmdMap is the `cmd` object of a batch request. It exists to keep the commands
// in SUBMISSION order on the wire.
//
// # Why not a plain map
//
// The server runs the commands in the order they appear in the JSON, and
// encoding/json writes a Go map with its keys SORTED. A plain map therefore
// reorders the batch alphabetically by command id, and a CHAINED batch then runs
// a consumer before its producer, with $result[…] pointing at nothing.
//
// It hides well. Auto-generated ids are cmd1, cmd2, cmd3 …, which sort into
// submission order — until the tenth, because "cmd10" sorts before "cmd2". A
// named command breaks it at once: AddAs("address_11", …) added after two
// auto-named producers runs FIRST, because "address_11" < "cmd1". That is how
// this was found — on a portal, as "ENTITY_ID is not defined or invalid" from a
// command whose ENTITY_ID was a $result reference to a requisite that had not
// been created yet.
//
// And it fails destructively rather than loudly. With Halt the batch stops with
// a confusing complaint from the consumer about a parameter it was never given.
// WITHOUT Halt the server does not treat an unresolved $result as an error at
// all: it substitutes the placeholder TEXT as a literal value, and the consumer
// commits a row built from that.
type cmdMap []cmdEntry
type cmdEntry struct {
ID CmdID
Call string
}
// MarshalJSON writes a JSON object whose members keep the slice's order.
func (c cmdMap) MarshalJSON() ([]byte, error) {
var buf bytes.Buffer
buf.WriteByte('{')
for i, e := range c {
if i > 0 {
buf.WriteByte(',')
}
key, err := json.Marshal(string(e.ID))
if err != nil {
return nil, err
}
call, err := json.Marshal(e.Call)
if err != nil {
return nil, err
}
buf.Write(key)
buf.WriteByte(':')
buf.Write(call)
}
buf.WriteByte('}')
return buf.Bytes(), nil
}
// paramsAsMap normalises a command's params to the map the query encoder needs.
// A struct is accepted the way Call accepts one, by going through JSON.
func paramsAsMap(params any) (map[string]any, error) {
switch v := params.(type) {
case nil:
return map[string]any{}, nil
case map[string]any:
return v, nil
}
raw, err := json.Marshal(params)
if err != nil {
return nil, fmt.Errorf("params do not marshal: %w", err)
}
var m map[string]any
if err := json.Unmarshal(raw, &m); err != nil {
return nil, fmt.Errorf("params are not a JSON object: %w", err)
}
return m, nil
}
// BatchResult holds one result per command.
type BatchResult struct {
// Order lists the command ids in submission order.
Order []CmdID
// Results holds the payload of each command that ran.
Results map[CmdID]json.RawMessage
// Errors holds the failure of each command that failed.
Errors map[CmdID]*APIError
// Next and Total carry the pagination metadata of list commands. The server
// lifts them OUT of each command's result into their own sections.
Next map[CmdID]int
Total map[CmdID]int
methods map[CmdID]string
}
// Get returns one command's result, or the error that command failed with.
//
// A command that never ran — because halt stopped the batch before it — yields
// an error saying so, which is a different thing from a command that ran and
// failed. Executed tells them apart without an error value.
func (r *BatchResult) Get(id CmdID) (json.RawMessage, error) {
if r == nil {
return nil, errors.New("b24gosdk: batch: nil result")
}
if e, ok := r.Errors[id]; ok {
return nil, e
}
if raw, ok := r.Results[id]; ok {
return raw, nil
}
if _, known := r.methods[id]; !known {
return nil, fmt.Errorf("b24gosdk: batch: no command %q", id)
}
return nil, fmt.Errorf("b24gosdk: batch: command %q did not run (halted earlier)", id)
}
// IDs decodes every command's result as an identifier, in submission order.
//
// # Why this exists
//
// "Create n things and get n ids back" is the batch a real integration writes,
// and reading the ids out of it is the same loop every time: walk Order, call
// Get, unmarshal into an ID, cope with the ones that failed. Written out at each
// call site it is a dozen lines whose only interesting part is the coping, which
// is exactly the part that gets skipped.
//
// res, err := client.Core().CallBatchChunked(ctx, b)
// ids, idErr := res.IDs() // ids[i] belongs to res.Order[i]
//
// # What a partial success returns
//
// A slice as long as Order, ALWAYS, positionally aligned with it — so ids[i] is
// the id of the i-th command added, and the alignment with whatever the caller
// built the batch from survives. A command that produced no identifier leaves a
// ZERO there (ID.IsZero) rather than shortening the slice: dropping the gaps
// would silently shift every id after the first failure onto the wrong entity.
//
// The error names every gap and wraps the underlying failures, so errors.Is and
// errors.As reach the *APIError of a command that failed. It is returned
// alongside the ids, never instead of them: the commands that succeeded have
// already committed on the portal, and a caller that drops the slice has no way
// to learn what exists.
//
// # It decodes the result AS the identifier
//
// That is what the classic add methods answer — crm.deal.add gives a bare id.
// A method that wraps it (crm.item.add answers {"item":{"id":…}}) or answers
// something else entirely (crm.deal.update answers true) is reported as a gap
// with its raw result quoted, rather than turned into a plausible 0. For those,
// read Get and Unwrap yourself.
func (r *BatchResult) IDs() ([]ID, error) {
if r == nil {
return nil, errors.New("b24gosdk: batch: nil result")
}
out := make([]ID, len(r.Order))
var errs []error
for i, cmd := range r.Order {
raw, err := r.Get(cmd)
if err != nil {
errs = append(errs, fmt.Errorf("b24gosdk: batch: %q (%s): %w", cmd, r.methods[cmd], err))
continue
}
var id ID
if err := json.Unmarshal(raw, &id); err != nil {
errs = append(errs, fmt.Errorf("b24gosdk: batch: %q (%s) answered %s, which is not an identifier; read it with Get",
cmd, r.methods[cmd], clip(raw)))
continue
}
// A command that succeeded and answered null or "" decodes to zero, which
// ID treats as an unset identifier — a normal Bitrix24 answer. Here it is
// not: nothing was identified, and letting the zero through would be the
// one gap in the slice with no error beside it.
if id.IsZero() {
errs = append(errs, fmt.Errorf("b24gosdk: batch: %q (%s) answered %s, which is no identifier at all",
cmd, r.methods[cmd], clip(raw)))
continue
}
out[i] = id
}
return out, errors.Join(errs...)
}
// clip shortens a result for an error message. A command that answered the wrong
// SHAPE may have answered a whole entity, and an error line is not the place to
// print one.
func clip(raw json.RawMessage) string {
const limit = 60
s := strings.TrimSpace(string(raw))
if len(s) <= limit {
return s
}
return s[:limit] + "…"
}
// Executed reports whether the command ran, whatever the outcome.
func (r *BatchResult) Executed(id CmdID) bool {
if r == nil {
return false
}
if _, ok := r.Results[id]; ok {
return true
}
_, ok := r.Errors[id]
return ok
}
// BatchError reports that at least one command in the batch failed.
//
// The batch itself succeeded at the transport level — the server answers HTTP
// 200 and puts per-command failures in result_error — so the result is returned
// ALONGSIDE this error and holds everything that did succeed. Do not discard it:
// retrying the whole batch would re-run the commands that already committed.
type BatchError struct {
Failed map[CmdID]*APIError
Result *BatchResult
}
func (e *BatchError) Error() string {
ids := make([]string, 0, len(e.Failed))
for id := range e.Failed {
ids = append(ids, string(id))
}
sort.Strings(ids)
if len(ids) == 1 {
return fmt.Sprintf("b24gosdk: batch: command %s failed: %v", ids[0], e.Failed[CmdID(ids[0])])
}
return fmt.Sprintf("b24gosdk: batch: %d commands failed: %s", len(ids), strings.Join(ids, ", "))
}
// Unwrap exposes the per-command errors to errors.Is and errors.As, so a caller
// can ask whether any command hit a particular API code.
func (e *BatchError) Unwrap() []error {
out := make([]error, 0, len(e.Failed))
for _, id := range e.sortedIDs() {
out = append(out, e.Failed[id])
}
return out
}
func (e *BatchError) sortedIDs() []CmdID {
ids := make([]CmdID, 0, len(e.Failed))
for id := range e.Failed {
ids = append(ids, id)
}
sort.Slice(ids, func(i, j int) bool { return ids[i] < ids[j] })
return ids
}
// CallBatch runs the batch in ONE request.
//
// It does not split: a batch longer than MaxBatchCommands is refused with
// ErrBatchLengthExceeded rather than sent, because the server would answer with
// what looks like a partial success. Use CallBatchChunked for many independent
// commands.
//
// err is non-nil when the call itself failed, AND when any command failed — in
// the latter case as a *BatchError, with the result still returned so the
// commands that succeeded are not lost.
//
// One request, but not a quick one: the commands run sequentially on the portal,
// so a batch of writes holds the connection for the sum of their durations —
// half a minute for 50 crm.deal.add. Give ctx a deadline that fits, and see
// Batch for what a timeout that fires costs.
//
// REST v1 only: on a v3 client it returns ErrV3BatchUnsupported.
func (c *Core) CallBatch(ctx context.Context, b *Batch) (*BatchResult, error) {
if c == nil || c.client == nil {
return nil, fmt.Errorf("b24gosdk: core is nil")
}
if b == nil || len(b.cmds) == 0 {
return nil, errors.New("b24gosdk: batch: no commands; an empty batch spends a rate-limit token for nothing")
}
if rest.IsV3(c.BaseURL()) {
return nil, ErrV3BatchUnsupported
}
if len(b.cmds) > MaxBatchCommands {
return nil, fmt.Errorf("%w: %d commands, the server takes at most %d; use CallBatchChunked",
ErrBatchLengthExceeded, len(b.cmds), MaxBatchCommands)
}
params, err := b.params()
if err != nil {
return nil, err
}
res, err := c.Call(ctx, batchMethod, params)
if err != nil {
return nil, err
}
return decodeBatchResult(b, res.Result)
}
// CallBatchChunked splits the batch at MaxBatchCommands, runs the pieces in
// order and merges the results.
//
// For INDEPENDENT commands only: a $result reference cannot cross a chunk
// boundary. For a chained batch use CallBatch, which keeps everything in one
// request.
//
// It returns what has been collected so far even when a chunk fails outright —
// earlier chunks have already committed on the portal, and a caller that drops
// the result has no way to know what exists.
func (c *Core) CallBatchChunked(ctx context.Context, b *Batch) (*BatchResult, error) {
if b == nil || len(b.cmds) == 0 {
return nil, errors.New("b24gosdk: batch: no commands; an empty batch spends a rate-limit token for nothing")
}
merged := newBatchResult(b)
var failed map[CmdID]*APIError
for _, chunk := range b.Chunks() {
res, err := c.CallBatch(ctx, chunk)
if res != nil {
mergeBatchResult(merged, res)
}
if err != nil {
var be *BatchError
if errors.As(err, &be) {
if failed == nil {
failed = map[CmdID]*APIError{}
}
for id, e := range be.Failed {
failed[id] = e
}
continue // per-command failures do not stop the remaining chunks
}
return merged, err // a transport-level failure does
}
}
if len(failed) > 0 {
return merged, &BatchError{Failed: failed, Result: merged}
}
return merged, nil
}
func newBatchResult(b *Batch) *BatchResult {
r := &BatchResult{
Results: map[CmdID]json.RawMessage{},
Errors: map[CmdID]*APIError{},
Next: map[CmdID]int{},
Total: map[CmdID]int{},
methods: map[CmdID]string{},
}
for _, c := range b.cmds {
r.Order = append(r.Order, c.ID)
r.methods[c.ID] = c.Method
}
return r
}
func mergeBatchResult(dst, src *BatchResult) {
for id, v := range src.Results {
dst.Results[id] = v
}
for id, v := range src.Errors {
dst.Errors[id] = v
}
for id, v := range src.Next {
dst.Next[id] = v
}
for id, v := range src.Total {
dst.Total[id] = v
}
}
// batchSections is the inner `result` of a batch envelope.
//
// The server renames on the way out — error -> result_error, total ->
// result_total, next -> result_next — which is why a $result placeholder names
// $result and never $result_next.
type batchSections struct {
Result flexMap `json:"result"`
Error flexMap `json:"result_error"`
Total flexMap `json:"result_total"`
Next flexMap `json:"result_next"`
}
// flexMap tolerates PHP's two spellings of an empty map.
//
// An empty PHP array encodes as [], a populated one as {}, and BOTH appear in a
// single batch envelope: the docs' own success example shows "result_error": []
// beside "result_total": {"get_department": 1}. A plain map field fails to
// decode the [] spelling and takes the whole envelope down with it.
type flexMap map[string]json.RawMessage
func (m *flexMap) UnmarshalJSON(b []byte) error {
trimmed := strings.TrimSpace(string(b))
if trimmed == "" || trimmed == "null" || trimmed == "[]" {
*m = flexMap{}
return nil
}
var raw map[string]json.RawMessage
if err := json.Unmarshal(b, &raw); err != nil {
return err
}
*m = raw
return nil
}
func decodeBatchResult(b *Batch, envelope json.RawMessage) (*BatchResult, error) {
res := newBatchResult(b)
var secs batchSections
// The outer `result` has the same []-vs-{} problem as its sections: a batch
// where nothing ran at all comes back as an empty array.
if trimmed := strings.TrimSpace(string(envelope)); trimmed != "" && trimmed != "null" && trimmed != "[]" {
if err := json.Unmarshal(envelope, &secs); err != nil {
return nil, fmt.Errorf("b24gosdk: batch: envelope did not decode: %w", err)
}
}
for k, raw := range secs.Result {
res.Results[CmdID(k)] = raw
}
for k, raw := range secs.Error {
res.Errors[CmdID(k)] = decodeBatchSubError(raw)
}
for k, raw := range secs.Next {
if n, err := strconv.Atoi(strings.Trim(string(raw), `"`)); err == nil {
res.Next[CmdID(k)] = n
}
}
for k, raw := range secs.Total {
if n, err := strconv.Atoi(strings.Trim(string(raw), `"`)); err == nil {
res.Total[CmdID(k)] = n
}
}
if len(res.Errors) > 0 {
return res, &BatchError{Failed: res.Errors, Result: res}
}
return res, nil
}
// decodeBatchSubError reads one entry of result_error.
//
// The server spells a sub-error two ways: an object {"error":…,
// "error_description":…} and, for some failures, a bare string. Both have to
// arrive as an *APIError, or a caller's errors.As stops working halfway through
// the error taxonomy.
func decodeBatchSubError(raw json.RawMessage) *APIError {
var obj struct {
Error string `json:"error"`
Description string `json:"error_description"`
}
if err := json.Unmarshal(raw, &obj); err == nil && (obj.Error != "" || obj.Description != "") {
return &APIError{Code: obj.Error, Description: obj.Description, RawBody: string(raw)}
}
var s string
if err := json.Unmarshal(raw, &s); err == nil {
return &APIError{Code: s, RawBody: string(raw)}
}
return &APIError{RawBody: string(raw)}
}
// Ref builds a placeholder the server substitutes with an earlier command's
// result:
//
// b24gosdk.Ref("get_user", "ID") // "$result[get_user][ID]"
// b24gosdk.Ref("new_contact") // "$result[new_contact]" — no path
//
// Pass NO path segments when the referenced command's result IS the value you
// want — crm.contact.add answers with a bare id, so Ref("new_contact") is right
// and Ref("new_contact", "ID") is not.
//
// The placeholder is an ORDINARY parameter value: do not pre-escape it. The
// server runs parse_str BEFORE substituting, so an encoded placeholder is
// decoded back before the substitution regex sees it.
//
// # What the server does that Ref cannot prevent
//
// - A missing path segment does NOT error. The walk stops at the last resolved
// ancestor and substitutes THAT, so a typo injects a whole object where a
// scalar was meant.
// - The placeholder is terminated by WHITESPACE and the replacement eats the
// whole match, so a SUFFIX is destroyed: "X" + Ref(...) + "-Y" loses the
// "-Y". A PREFIX survives, because the match begins at the '$' — which is
// the form Bitrix24's own documentation uses for file fields, where the disk
// object id wants an "n" in front ("n" + Ref(...) -> n2107).
// - Substitution also runs on parameter KEYS, where it resolves to nothing.
// Placeholders belong in values.
//
// Ref refuses an id or segment containing whitespace, '$', '[' or ']', and
// returns the error rather than a placeholder the server would misread: a
// malformed placeholder does not fail server-side, it silently substitutes the
// wrong value. Every error wraps ErrBadRef.
func Ref(id CmdID, path ...string) (string, error) {
if err := checkRefPart(string(id), "command id"); err != nil {
return "", err
}
var sb strings.Builder
sb.WriteString("$result[")
sb.WriteString(string(id))
sb.WriteString("]")
for _, seg := range path {
if err := checkRefPart(seg, "path segment"); err != nil {
return "", err
}
sb.WriteString("[")
sb.WriteString(seg)
sb.WriteString("]")
}
return sb.String(), nil
}
func checkRefPart(s, what string) error {
if s == "" {
return fmt.Errorf("%w: empty %s", ErrBadRef, what)
}
if strings.ContainsAny(s, " \t\n\r") {
return fmt.Errorf("%w: %s %q contains whitespace, which terminates the placeholder", ErrBadRef, what, s)
}
if strings.ContainsAny(s, "$[]") {
return fmt.Errorf("%w: %s %q contains one of $[], which the server would misparse", ErrBadRef, what, s)
}
return nil
}