1
//go:generate mockgen -source=base.go -destination=mocks/mock_base.go -package=mocks
2
package shared
3

            
4
import (
5
	"strings"
6
	"unsafe"
7
)
8

            
9
// UnsafeEnvoyBuffer is a struct that represents a buffer of data from Envoy.
10
// It contains a pointer to the data and its length. The memory of the data is managed by Envoy.
11
type UnsafeEnvoyBuffer struct {
12
	// Pointer to the start of the buffer data.
13
	Ptr *byte
14
	// Length of the buffer data in bytes.
15
	Len uint64
16
}
17

            
18
func (b UnsafeEnvoyBuffer) ToUnsafeBytes() []byte {
19
	if b.Ptr == nil || b.Len == 0 {
20
		return nil
21
	}
22
	// Use unsafe to create a byte slice that points to the buffer data without copying.
23
	return unsafe.Slice(b.Ptr, b.Len)
24
}
25

            
26
// ToBytes converts the UnsafeEnvoyBuffer to a byte slice. It creates a copy of the data in Go memory.
27
func (b UnsafeEnvoyBuffer) ToBytes() []byte {
28
	if b.Ptr == nil || b.Len == 0 {
29
		return nil
30
	}
31
	// Create a byte slice that copys the data from the buffer.
32
	owned := make([]byte, b.Len)
33
	// Use unsafe to copy the data from the buffer to the byte slice.
34
	src := unsafe.Slice(b.Ptr, b.Len)
35
	copy(owned, src)
36
	return owned
37
}
38

            
39
func (b UnsafeEnvoyBuffer) ToUnsafeString() string {
40
	if b.Ptr == nil || b.Len == 0 {
41
		return ""
42
	}
43
	// Use unsafe to create a string that points to the buffer data without copying.
44
	return unsafe.String(b.Ptr, b.Len)
45
}
46

            
47
func (b UnsafeEnvoyBuffer) ToString() string {
48
	if b.Ptr == nil || b.Len == 0 {
49
		return ""
50
	}
51
	return strings.Clone(b.ToUnsafeString())
52
}
53

            
54
// BodyBuffer is an interface that provides access to the request and response body.
55
// This should be implemented by the SDK or runtime.
56
type BodyBuffer interface {
57
	// GetChunks retrieves the body content as a list of UnsafeEnvoyBuffer chunks.
58
	// NOTE: The memory of underlying data may not be managed by Go GC. So you should
59
	// copy the data if you need to keep it and use it later.
60
	GetChunks() []UnsafeEnvoyBuffer
61

            
62
	// GetSize retrieves the total size of the body buffer.
63
	GetSize() uint64
64

            
65
	// Drain removes the specified number of bytes from the beginning of the body buffer.
66
	// @Param numBytes the number of bytes to drain.
67
	Drain(numBytes uint64)
68

            
69
	// Append adds the specified bytes to the end of the body buffer.
70
	// @Param data the bytes to append.
71
	Append(data []byte)
72
}
73

            
74
// HeaderMap is an interface that provides access to the request and response headers.
75
// This should be implemented by the SDK or runtime.
76
type HeaderMap interface {
77
	// Get retrieves the header values for a given key. If the key does not exist,
78
	// nil will be returned.
79
	// NOTE: The memory of underlying data may not be managed by Go GC. So you should
80
	// copy the data if you need to keep it and use it later.
81
	Get(key string) []UnsafeEnvoyBuffer
82

            
83
	// GetOne retrieves a single header value for a given key.
84
	// If there are multiple values for the key, the first one will be returned.
85
	// If the key does not exist, an empty UnsafeEnvoyBuffer will be returned.
86
	// NOTE: The memory of underlying data may not be managed by Go GC. So you should
87
	// copy the data if you need to keep it and use it later.
88
	GetOne(key string) UnsafeEnvoyBuffer
89

            
90
	// GetAll retrieves all header values. You should not mutate the returned slice
91
	// directly.
92
	// NOTE: The memory of underlying data may not be managed by Go GC. So you should
93
	// copy the data if you need to keep it and use it later.
94
	GetAll() [][2]UnsafeEnvoyBuffer
95

            
96
	// Set sets the header value for a given key.
97
	Set(key string, value string)
98

            
99
	// Add adds a single header value for a given key.
100
	Add(key string, value string)
101

            
102
	// Remove removes the header values for a given key.
103
	Remove(key string)
104
}
105

            
106
type AttributeID uint32
107

            
108
const (
109
	// request.path
110
	AttributeIDRequestPath AttributeID = iota
111
	// request.url_path
112
	AttributeIDRequestUrlPath
113
	// request.host
114
	AttributeIDRequestHost
115
	// request.scheme
116
	AttributeIDRequestScheme
117
	// request.method
118
	AttributeIDRequestMethod
119
	// request.headers
120
	AttributeIDRequestHeaders
121
	// request.referer
122
	AttributeIDRequestReferer
123
	// request.useragent
124
	AttributeIDRequestUserAgent
125
	// request.time
126
	AttributeIDRequestTime
127
	// request.id
128
	AttributeIDRequestId
129
	// request.protocol
130
	AttributeIDRequestProtocol
131
	// request.query
132
	AttributeIDRequestQuery
133
	// request.duration
134
	AttributeIDRequestDuration
135
	// request.size
136
	AttributeIDRequestSize
137
	// request.total_size
138
	AttributeIDRequestTotalSize
139
	// response.code
140
	AttributeIDResponseCode
141
	// response.code_details
142
	AttributeIDResponseCodeDetails
143
	// response.flags
144
	AttributeIDResponseFlags
145
	// response.grpc_status
146
	AttributeIDResponseGrpcStatus
147
	// response.headers
148
	AttributeIDResponseHeaders
149
	// response.trailers
150
	AttributeIDResponseTrailers
151
	// response.size
152
	AttributeIDResponseSize
153
	// response.total_size
154
	AttributeIDResponseTotalSize
155
	// response.backend_latency
156
	AttributeIDResponseBackendLatency
157
	// source.address
158
	AttributeIDSourceAddress
159
	// source.port
160
	AttributeIDSourcePort
161
	// destination.address
162
	AttributeIDDestinationAddress
163
	// destination.port
164
	AttributeIDDestinationPort
165
	// connection.id
166
	AttributeIDConnectionId
167
	// connection.mtls
168
	AttributeIDConnectionMtls
169
	// connection.requested_server_name
170
	AttributeIDConnectionRequestedServerName
171
	// connection.tls_version
172
	AttributeIDConnectionTlsVersion
173
	// connection.subject_local_certificate
174
	AttributeIDConnectionSubjectLocalCertificate
175
	// connection.subject_peer_certificate
176
	AttributeIDConnectionSubjectPeerCertificate
177
	// connection.dns_san_local_certificate
178
	AttributeIDConnectionDnsSanLocalCertificate
179
	// connection.dns_san_peer_certificate
180
	AttributeIDConnectionDnsSanPeerCertificate
181
	// connection.uri_san_local_certificate
182
	AttributeIDConnectionUriSanLocalCertificate
183
	// connection.uri_san_peer_certificate
184
	AttributeIDConnectionUriSanPeerCertificate
185
	// connection.sha256_peer_certificate_digest
186
	AttributeIDConnectionSha256PeerCertificateDigest
187
	// connection.transport_failure_reason
188
	AttributeIDConnectionTransportFailureReason
189
	// connection.termination_details
190
	AttributeIDConnectionTerminationDetails
191
	// upstream.address
192
	AttributeIDUpstreamAddress
193
	// upstream.port
194
	AttributeIDUpstreamPort
195
	// upstream.tls_version
196
	AttributeIDUpstreamTlsVersion
197
	// upstream.subject_local_certificate
198
	AttributeIDUpstreamSubjectLocalCertificate
199
	// upstream.subject_peer_certificate
200
	AttributeIDUpstreamSubjectPeerCertificate
201
	// upstream.dns_san_local_certificate
202
	AttributeIDUpstreamDnsSanLocalCertificate
203
	// upstream.dns_san_peer_certificate
204
	AttributeIDUpstreamDnsSanPeerCertificate
205
	// upstream.uri_san_local_certificate
206
	AttributeIDUpstreamUriSanLocalCertificate
207
	// upstream.uri_san_peer_certificate
208
	AttributeIDUpstreamUriSanPeerCertificate
209
	// upstream.sha256_peer_certificate_digest
210
	AttributeIDUpstreamSha256PeerCertificateDigest
211
	// upstream.local_address
212
	AttributeIDUpstreamLocalAddress
213
	// upstream.transport_failure_reason
214
	AttributeIDUpstreamTransportFailureReason
215
	// upstream.request_attempt_count
216
	AttributeIDUpstreamRequestAttemptCount
217
	// upstream.cx_pool_ready_duration
218
	AttributeIDUpstreamCxPoolReadyDuration
219
	// upstream.locality
220
	AttributeIDUpstreamLocality
221
	// xds.node
222
	AttributeIDXdsNode
223
	// xds.cluster_name
224
	AttributeIDXdsClusterName
225
	// xds.cluster_metadata
226
	AttributeIDXdsClusterMetadata
227
	// xds.listener_direction
228
	AttributeIDXdsListenerDirection
229
	// xds.listener_metadata
230
	AttributeIDXdsListenerMetadata
231
	// xds.route_name
232
	AttributeIDXdsRouteName
233
	// xds.route_metadata
234
	AttributeIDXdsRouteMetadata
235
	// xds.virtual_host_name
236
	AttributeIDXdsVirtualHostName
237
	// xds.virtual_host_metadata
238
	AttributeIDXdsVirtualHostMetadata
239
	// xds.upstream_host_metadata
240
	AttributeIDXdsUpstreamHostMetadata
241
	// xds.filter_chain_name
242
	AttributeIDXdsFilterChainName
243
)
244

            
245
type LogLevel uint32
246

            
247
const (
248
	LogLevelTrace LogLevel = iota
249
	LogLevelDebug
250
	LogLevelInfo
251
	LogLevelWarn
252
	LogLevelError
253
	LogLevelCritical
254
	LogLevelOff
255
)
256

            
257
type HttpCalloutInitResult uint32
258

            
259
const (
260
	HttpCalloutInitSuccess HttpCalloutInitResult = iota
261
	HttpCalloutInitMissingRequiredHeaders
262
	HttpCalloutInitClusterNotFound
263
	HttpCalloutInitDuplicateCalloutId
264
	HttpCalloutInitCannotCreateRequest
265
)
266

            
267
type HttpCalloutResult uint32
268

            
269
const (
270
	HttpCalloutSuccess HttpCalloutResult = iota
271
	HttpCalloutReset
272
	HttpCalloutExceedResponseBufferLimit
273
)
274

            
275
type MetadataSourceType uint32
276

            
277
const (
278
	MetadataSourceTypeDynamic MetadataSourceType = iota
279
	MetadataSourceTypeRoute
280
	MetadataSourceTypeCluster
281
	MetadataSourceTypeHost
282
	MetadataSourceTypeHostLocality
283
)
284

            
285
type HttpCalloutCallback interface {
286
	OnHttpCalloutDone(calloutID uint64, result HttpCalloutResult,
287
		headers [][2]UnsafeEnvoyBuffer, body []UnsafeEnvoyBuffer)
288
}
289

            
290
type HttpStreamResetReason uint32
291

            
292
const (
293
	HttpStreamResetReasonConnectionFailure = iota
294
	HttpStreamResetReasonConnectionTermination
295
	HttpStreamResetReasonLocalReset
296
	HttpStreamResetReasonLocalRefusedStreamReset
297
	HttpStreamResetReasonOverflow
298
	HttpStreamResetReasonRemoteReset
299
	HttpStreamResetReasonRemoteRefusedStreamReset
300
	HttpStreamResetReasonProtocolError
301
)
302

            
303
type HttpStreamCallback interface {
304
	OnHttpStreamHeaders(streamID uint64, headers [][2]UnsafeEnvoyBuffer, endStream bool)
305
	OnHttpStreamData(streamID uint64, body []UnsafeEnvoyBuffer, endStream bool)
306
	OnHttpStreamTrailers(streamID uint64, trailers [][2]UnsafeEnvoyBuffer)
307
	OnHttpStreamComplete(streamID uint64)
308
	OnHttpStreamReset(streamID uint64, reason HttpStreamResetReason)
309
}
310

            
311
// Scheduler is the interface that provides scheduling capabilities for asynchronous operations.
312
// This allow the plugins run tasks in another thread and continue the processing later at the
313
// thread where the stream plugin is being processed.
314
type Scheduler interface {
315
	// Schedule schedules a function to be executed asynchronously in the thread where the stream
316
	// plugin is being processed.
317
	// @Param func the function to be executed.
318
	// NOTE: This function may be ignored if the related plugin processing is completed.
319
	Schedule(func())
320
}
321

            
322
type DownstreamWatermarkCallbacks interface {
323
	OnAboveWriteBufferHighWatermark()
324
	OnBelowWriteBufferLowWatermark()
325
}
326

            
327
// HttpFilterHandle is the interface that provides access to the plugin's context and configuration.
328
// This should be implemented by the SDK or runtime.
329
type HttpFilterHandle interface {
330
	// GetMetadataString retrieves the dynamic metadata string value of the stream.
331
	// @Param source the metadata source type.
332
	// @Param metadataNamespace the metadata namespace.
333
	// @Param key the metadata key.
334
	// @Return the metadata value if found, otherwise an empty UnsafeEnvoyBuffer.
335
	GetMetadataString(source MetadataSourceType, metadataNamespace, key string) (UnsafeEnvoyBuffer, bool)
336

            
337
	// GetMetadataNumber retrieves the dynamic metadata number value of the stream.
338
	// @Param source the metadata source type.
339
	// @Param metadataNamespace the metadata namespace.
340
	// @Param key the metadata key.
341
	// @Return the metadata value if found, otherwise nil.
342
	GetMetadataNumber(source MetadataSourceType, metadataNamespace, key string) (float64, bool)
343

            
344
	// GetMetadataBool retrieves the dynamic metadata bool value of the stream.
345
	// @Param source the metadata source type.
346
	// @Param metadataNamespace the metadata namespace.
347
	// @Param key the metadata key.
348
	// @Return the metadata value and true if found, otherwise false.
349
	GetMetadataBool(source MetadataSourceType, metadataNamespace, key string) (bool, bool)
350

            
351
	// SetMetadata sets the dynamic metadata value of the stream.
352
	// @Param metadataNamespace the metadata namespace.
353
	// @Param key the metadata key.
354
	// @Param value the metadata value. Only string/int/float/bool are supported.
355
	SetMetadata(metadataNamespace, key string, value any)
356

            
357
	// GetMetadataKeys retrieves all keys in the given metadata namespace.
358
	// @Param source the metadata source type.
359
	// @Param metadataNamespace the metadata namespace.
360
	// @Return the list of keys in the namespace, or nil if the namespace does not exist.
361
	// NOTE: The memory of underlying data may not be managed by Go GC. So you should
362
	// copy the data if you need to keep it and use it later.
363
	GetMetadataKeys(source MetadataSourceType, metadataNamespace string) []UnsafeEnvoyBuffer
364

            
365
	// GetMetadataNamespaces retrieves all namespace names in the metadata.
366
	// @Param source the metadata source type.
367
	// @Return the list of namespace names, or nil if no namespaces exist.
368
	// NOTE: The memory of underlying data may not be managed by Go GC. So you should
369
	// copy the data if you need to keep it and use it later.
370
	GetMetadataNamespaces(source MetadataSourceType) []UnsafeEnvoyBuffer
371

            
372
	// AddMetadataListNumber appends a number value to the dynamic metadata list stored under the
373
	// given namespace and key. If the key does not exist, a new list is created. Returns false if
374
	// the key exists but is not a list, or if the metadata is not accessible.
375
	AddMetadataListNumber(metadataNamespace, key string, value float64) bool
376

            
377
	// AddMetadataListString appends a string value to the dynamic metadata list stored under the
378
	// given namespace and key. If the key does not exist, a new list is created. Returns false if
379
	// the key exists but is not a list, or if the metadata is not accessible.
380
	AddMetadataListString(metadataNamespace, key string, value string) bool
381

            
382
	// AddMetadataListBool appends a bool value to the dynamic metadata list stored under the
383
	// given namespace and key. If the key does not exist, a new list is created. Returns false if
384
	// the key exists but is not a list, or if the metadata is not accessible.
385
	AddMetadataListBool(metadataNamespace, key string, value bool) bool
386

            
387
	// GetMetadataListSize returns the number of elements in the metadata list stored under the
388
	// given namespace and key. Returns (0, false) if the metadata is not accessible, the namespace
389
	// or key does not exist, or the value is not a list.
390
	GetMetadataListSize(source MetadataSourceType, metadataNamespace, key string) (int, bool)
391

            
392
	// GetMetadataListNumber returns the number element at the given index in the metadata list
393
	// stored under the given namespace and key. Returns (0, false) if the metadata is not
394
	// accessible, the namespace or key does not exist, the value is not a list, the index is out
395
	// of range, or the element is not a number.
396
	GetMetadataListNumber(source MetadataSourceType, metadataNamespace, key string, index int) (float64, bool)
397

            
398
	// GetMetadataListString returns the string element at the given index in the metadata list
399
	// stored under the given namespace and key. Returns an empty buffer and false if the metadata is
400
	// not accessible, the namespace or key does not exist, the value is not a list, the index is
401
	// out of range, or the element is not a string.
402
	// NOTE: The memory of underlying data may not be managed by Go GC. So you should
403
	// copy the data if you need to keep it and use it later.
404
	GetMetadataListString(source MetadataSourceType, metadataNamespace, key string, index int) (UnsafeEnvoyBuffer, bool)
405

            
406
	// GetMetadataListBool returns the bool element at the given index in the metadata list stored
407
	// under the given namespace and key. Returns (false, false) if the metadata is not accessible,
408
	// the namespace or key does not exist, the value is not a list, the index is out of range, or
409
	// the element is not a bool.
410
	GetMetadataListBool(source MetadataSourceType, metadataNamespace, key string, index int) (bool, bool)
411

            
412
	// GetFilterState retrieves the serialized filter state value of the stream.
413
	// @Param key the filter state key.
414
	// @Return the filter state value if found, otherwise an empty UnsafeEnvoyBuffer.
415
	// NOTE: The memory of underlying data may not be managed by Go GC. So you should
416
	// copy the data if you need to keep it and use it later.
417
	GetFilterState(key string) (UnsafeEnvoyBuffer, bool)
418

            
419
	// SetFilterState sets the serialized filter state value of the stream.
420
	// @Param key the filter state key.
421
	// @Param value the filter state value.
422
	SetFilterState(key string, value []byte)
423

            
424
	// GetAttributeString retrieves the string attribute value of the stream.
425
	// @Param attributeID the attribute ID.
426
	// @Return the attribute value if found, otherwise an empty UnsafeEnvoyBuffer.
427
	// NOTE: The memory of underlying data may not be managed by Go GC. So you should
428
	// copy the data if you need to keep it and use it later.
429
	GetAttributeString(attributeID AttributeID) (UnsafeEnvoyBuffer, bool)
430

            
431
	// GetAttributeNumber retrieves the float attribute value of the stream.
432
	// @Param key the attribute key.
433
	// @Return the attribute value if found, otherwise nil.
434
	GetAttributeNumber(attributeID AttributeID) (float64, bool)
435

            
436
	// GetAttributeBool retrieves the bool attribute value of the stream.
437
	// @Param attributeID the attribute ID.
438
	// @Return the attribute value and true if found, otherwise false.
439
	GetAttributeBool(attributeID AttributeID) (bool, bool)
440

            
441
	// GetData retrieves internal data stored for cross-phase communication.
442
	// This data is not included in DynamicMetadata responses.
443
	// @Param key the data key.
444
	// @Return the data value if found, otherwise nil.
445
	GetData(key string) any
446

            
447
	// SetData sets internal data for cross-phase communication.
448
	// This data is not included in DynamicMetadata responses.
449
	// @Param key the data key.
450
	// @Param value the data value.
451
	SetData(key string, value any)
452

            
453
	// SendLocalResponse sends a local reply to the client and terminates the stream.
454
	// @Param status the HTTP status code.
455
	// @Param headers the response headers.
456
	// @Param body the response body.
457
	// @Param detail a short description to the response for debugging purposes.
458
	SendLocalResponse(status uint32, headers [][2]string, body []byte, detail string)
459

            
460
	// SendResponseHeaders sends response headers to the client. This is used for
461
	// streaming local replies.
462
	//
463
	// @Param headers the response headers.
464
	// @Param endOfStream whether this is the end of the stream.
465
	SendResponseHeaders(headers [][2]string, endOfStream bool)
466

            
467
	// SendResponseData sends response body data to the client. This is used for
468
	// streaming local replies.
469
	//
470
	// @Param body the response body data.
471
	// @Param endOfStream whether this is the end of the stream.
472
	SendResponseData(body []byte, endOfStream bool)
473

            
474
	// SendResponseTrailers sends response trailers to the client. This is used for
475
	// streaming local replies.
476
	//
477
	// @Param trailers the response trailers.
478
	SendResponseTrailers(trailers [][2]string)
479

            
480
	// AddCustomFlag adds a custom flag to the stream. This flag should be very short
481
	// string to indicate some custom state or information of the stream.
482
	// @Param flag the custom flag to add.
483
	AddCustomFlag(flag string)
484

            
485
	// ContinueRequest continues the request stream processing.
486
	// NOTE: This function should only be called when the plugin chains are hung up because
487
	// of asynchronous operations.
488
	ContinueRequest()
489

            
490
	// ContinueResponse continues the response stream processing.
491
	// NOTE: This function should only be called when the plugin chains are hung up because
492
	// of asynchronous operations.
493
	ContinueResponse()
494

            
495
	// ClearRouteCache clears the cached route for the stream.
496
	ClearRouteCache()
497

            
498
	// RequestHeaders retrieves the request headers.
499
	// @Return the request headers.
500
	RequestHeaders() HeaderMap
501

            
502
	// BufferedRequestBody retrieves the buffered request body in the chain.
503
	// NOTE: Different with the headers and trailers, because of the streaming processing,
504
	// the request body is not always fully buffered. So this function only retrieves the
505
	// currently buffered body in the chain. And the latest newly received body chunk is passed
506
	// as the parameter to OnRequestBody. Only when endOfStream is true or OnRequestTrailers is
507
	// called, the full request body is received.
508
	// @Return the buffered request body.
509
	BufferedRequestBody() BodyBuffer
510

            
511
	// ReceivedRequestBody retrieves the latest received request body chunk in the OnRequestBody callback.
512
	// NOTE: This is only valid in the OnRequestBody callback, and it retrieves the latest received
513
	// body chunk that triggers the callback. For other callbacks or outside of the callbacks, you
514
	// should use BufferedRequestBody to get the currently buffered body in the chain.
515
	ReceivedRequestBody() BodyBuffer
516

            
517
	// RequestTrailers retrieves the request trailers.
518
	// @Return the request trailers.
519
	RequestTrailers() HeaderMap
520

            
521
	// ResponseHeaders retrieves the response headers.
522
	// @Return the response headers.
523
	ResponseHeaders() HeaderMap
524

            
525
	// BufferedResponseBody retrieves the buffered response body in the chain.
526
	// NOTE: Different with the headers and trailers, because of the streaming processing,
527
	// the request body is not always fully buffered. So this function only retrieves the
528
	// currently buffered body in the chain. And the latest newly received body chunk is passed
529
	// as the parameter to OnResponseBody. Only when endOfStream is true or OnResponseTrailers is
530
	// called, the full request body is received.
531
	// @Return the buffered response body.
532
	BufferedResponseBody() BodyBuffer
533

            
534
	// ReceivedResponseBody retrieves the latest received response body chunk in the OnResponseBody callback.
535
	// NOTE: This is only valid in the OnResponseBody callback, and it retrieves the latest received
536
	// body chunk that triggers the callback. For other callbacks or outside of the callbacks, you
537
	// should use BufferedResponseBody to get the currently buffered body in the chain.
538
	ReceivedResponseBody() BodyBuffer
539

            
540
	// ReceivedBufferedRequestBody returns true if the latest received request body is the
541
	// previously buffered request body. This is true when a previous filter in the chain stopped
542
	// and buffered the request body, then resumed, and this filter is now receiving that buffered
543
	// body.
544
	// NOTE: This is only meaningful inside the OnRequestBody callback.
545
	ReceivedBufferedRequestBody() bool
546

            
547
	// ReceivedBufferedResponseBody returns true if the latest received response body is the
548
	// previously buffered response body. This is true when a previous filter in the chain stopped
549
	// and buffered the response body, then resumed, and this filter is now receiving that buffered
550
	// body.
551
	// NOTE: This is only meaningful inside the OnResponseBody callback.
552
	ReceivedBufferedResponseBody() bool
553

            
554
	// ResponseTrailers retrieves the response trailers.
555
	// @Return the response trailers.
556
	ResponseTrailers() HeaderMap
557

            
558
	// GetMostSpecificConfig retrieves the most specific route configuration for the stream.
559
	GetMostSpecificConfig() any
560

            
561
	// GetScheduler retrieves the scheduler related to this stream plugin for asynchronous
562
	// operations.
563
	//
564
	// NOTE: This MUST only be called during OnRequest* or OnResponse* callbacks. But then the
565
	// returned Scheduler can be used later even outside of the callbacks and even at other
566
	// threads.
567
	GetScheduler() Scheduler
568

            
569
	// Log will log the given message via the host environment's logging mechanism.
570
	Log(level LogLevel, format string, args ...any)
571

            
572
	// HttpCallout performs an HTTP call to an external service. The call is asynchronous, and the
573
	// response will be delivered via the provided callback.
574
	// @Param cluster the cluster (target) name to which the HTTP call will be made.
575
	// @Param headers the HTTP headers to be sent with the request.
576
	// @Param body the HTTP body to be sent with the request.
577
	// @Param timeoutMs the timeout in milliseconds for the HTTP call.
578
	// @Param callback the callback function to be invoked when the response is received or an
579
	// error occurs.
580
	// The callback function receives the response headers, body, and an error if any occurred.
581
	//
582
	// @Return the result of the HTTP callout initialization and the callout ID. Non-success results
583
	// indicate that the callout failed to start.
584
	//
585
	// NOTE: This method should only be called during OnRequest* or OnResponse* callbacks or
586
	// scheduled functions via the Scheduler. By this way we can ensure this is only be called
587
	// in the thread where the stream plugin is being processed.
588
	HttpCallout(cluster string, headers [][2]string, body []byte, timeoutMs uint64,
589
		cb HttpCalloutCallback) (HttpCalloutInitResult, uint64)
590

            
591
	// StartHttpStream starts a new HTTP stream to an external service. The stream is asynchronous,
592
	// and the response will be delivered via the provided callback.
593
	// @Param cluster the cluster (target) name to which the HTTP stream will be made.
594
	// @Param headers the initial HTTP headers to be sent with the request.
595
	// @Param body the initial HTTP body to be sent with the request.
596
	// @Param endOfStream whether this is the end of the stream.
597
	// @Param timeoutMs the timeout in milliseconds for the HTTP stream.
598
	// @Param callback the callback interface to handle the stream events.
599
	//
600
	// @Return the result of the HTTP stream initialization and the stream ID. Non-success results
601
	// indicate that the stream failed to start.
602
	//
603
	// NOTE: This method should only be called during OnRequest* or OnResponse* callbacks or
604
	// scheduled functions via the Scheduler. By this way we can ensure this is only be called
605
	// in the thread where the stream plugin is being processed.
606
	StartHttpStream(cluster string, headers [][2]string, body []byte, endOfStream bool, timeoutMs uint64,
607
		cb HttpStreamCallback) (HttpCalloutInitResult, uint64)
608

            
609
	// SendHttpStreamData sends data on an existing HTTP stream.
610
	// @Param streamID the ID of the HTTP stream.
611
	// @Param body the HTTP body to be sent with the request.
612
	// @Param endOfStream whether this is the end of the stream.
613
	//
614
	// @Return whether the data was successfully sent.
615
	//
616
	// NOTE: This method should only be called during OnRequest* or OnResponse* callbacks or
617
	// scheduled functions via the Scheduler. By this way we can ensure this is only be called
618
	// in the thread where the stream plugin is being processed.
619
	SendHttpStreamData(streamID uint64, body []byte, endOfStream bool) bool
620

            
621
	// SendHttpStreamTrailers sends trailers on an existing HTTP stream.
622
	// @Param streamID the ID of the HTTP stream.
623
	// @Param trailers the HTTP trailers to be sent with the request.
624
	//
625
	// @Return whether the trailers were successfully sent.
626
	//
627
	// NOTE: This method should only be called during OnRequest* or OnResponse* callbacks or
628
	// scheduled functions via the Scheduler. By this way we can ensure this is only be called
629
	// in the thread where the stream plugin is being processed.
630
	SendHttpStreamTrailers(streamID uint64, trailers [][2]string) bool
631

            
632
	// ResetHttpStream resets an existing HTTP stream.
633
	// @Param streamID the ID of the HTTP stream.
634
	//
635
	// NOTE: This method should only be called during OnRequest* or OnResponse* callbacks or
636
	// scheduled functions via the Scheduler. By this way we can ensure this is only be called
637
	// in the thread where the stream plugin is being processed.
638
	ResetHttpStream(streamID uint64)
639

            
640
	// SetDownstreamWatermarkCallbacks sets the downstream watermark callbacks for the stream.
641
	// @Param callbacks the downstream watermark callbacks.
642
	SetDownstreamWatermarkCallbacks(callbacks DownstreamWatermarkCallbacks)
643

            
644
	// ClearDownstreamWatermarkCallbacks unsets the downstream watermark callbacks for the stream.
645
	ClearDownstreamWatermarkCallbacks()
646

            
647
	// RecordValue records the given value to the histogram metric.
648
	// @Param id the histogram metric id.
649
	// @Param value the value to be recorded.
650
	// @Param tagsValues the optional tag values associated with the metric. The order and size
651
	// of the tag values must match the tag keys defined when the metric was created.
652
	RecordHistogramValue(id MetricID, value uint64, tagsValues ...string) MetricsResult
653

            
654
	// SetValue sets the given value to the gauge metric.
655
	// @Param id the gauge metric id.
656
	// @Param value the value to be set.
657
	// @Param tagsValues the optional tag values associated with the metric. The order and size
658
	// of the tag values must match the tag keys defined when the metric was created.
659
	SetGaugeValue(id MetricID, value uint64, tagsValues ...string) MetricsResult
660

            
661
	// IncrementGaugeValue adds the given value to the gauge metric.
662
	// @Param id the gauge metric id.
663
	// @Param value the value to be added.
664
	// @Param tagsValues the optional tag values associated with the metric. The order and size
665
	// of the tag values must match the tag keys defined when the metric was created.
666
	IncrementGaugeValue(id MetricID, value uint64, tagsValues ...string) MetricsResult
667

            
668
	// DecrementGaugeValue subtracts the given value from the gauge metric.
669
	// @Param id the gauge metric id.
670
	// @Param value the value to be subtracted.
671
	// @Param tagsValues the optional tag values associated with the metric. The order and size
672
	// of the tag values must match the tag keys defined when the metric was created.
673
	DecrementGaugeValue(id MetricID, value uint64, tagsValues ...string) MetricsResult
674

            
675
	// IncrementCounterValue adds the given value to the counter metric.
676
	// @Param id the counter metric id.
677
	// @Param value the value to be added.
678
	// @Param tagsValues the optional tag values associated with the metric. The order and size
679
	// of the tag values must match the tag keys defined when the metric was created.
680
	IncrementCounterValue(id MetricID, value uint64, tagsValues ...string) MetricsResult
681
}
682

            
683
type MetricID uint64
684
type MetricsResult uint32
685

            
686
const (
687
	MetricsSuccess MetricsResult = iota
688
	MetricsNotFound
689
	MetricsInvalidTags
690
	MetricsFrozen
691
)
692

            
693
type HttpFilterConfigHandle interface {
694
	// Log will log the given message via the host environment's logging mechanism.
695
	Log(level LogLevel, format string, args ...any)
696

            
697
	// DefineHistogram creates a histogram metric with the given name, and tag keys.
698
	// @Param name the name of the metric.
699
	// @Param tagKeys the optional tag keys for the metric.
700
	// @Return the histogram metric id. This metric can never be used after the plugin
701
	// config is unloaded.
702
	DefineHistogram(name string, tagKeys ...string) (MetricID, MetricsResult)
703

            
704
	// DefineGauge creates a gauge metric with the given name, description, and tag keys.
705
	// @Param name the name of the metric.
706
	// @Param tagKeys the optional tag keys for the metric.
707
	// @Return the gauge metric id. This metric can never be used after the plugin
708
	// config is unloaded.
709
	DefineGauge(name string, tagKeys ...string) (MetricID, MetricsResult)
710

            
711
	// DefineCounter creates a counter metric with the given name, description, and tag keys.
712
	// @Param name the name of the metric.
713
	// @Param tagKeys the optional tag keys for the metric.
714
	// @Return the counter metric id. This metric can never be used after the plugin
715
	// config is unloaded.
716
	DefineCounter(name string, tagKeys ...string) (MetricID, MetricsResult)
717

            
718
	// HttpCallout performs an HTTP call to an external service from the config context.
719
	// The call is asynchronous, and the response will be delivered via the provided callback.
720
	// This is similar to HttpFilterHandle.HttpCallout but runs on the main thread rather than
721
	// the worker thread.
722
	// @Param cluster the cluster (target) name to which the HTTP call will be made.
723
	// @Param headers the HTTP headers to be sent with the request.
724
	// @Param body the HTTP body to be sent with the request.
725
	// @Param timeoutMs the timeout in milliseconds for the HTTP call.
726
	// @Param callback the callback function to be invoked when the response is received.
727
	// @Return the result of the HTTP callout initialization and the callout ID.
728
	HttpCallout(cluster string, headers [][2]string, body []byte, timeoutMs uint64,
729
		cb HttpCalloutCallback) (HttpCalloutInitResult, uint64)
730

            
731
	// StartHttpStream starts a new HTTP stream to an external service from the config context.
732
	// The stream is asynchronous, and the response will be delivered via the provided callback.
733
	// This is similar to HttpFilterHandle.StartHttpStream but runs on the main thread.
734
	// @Param cluster the cluster (target) name.
735
	// @Param headers the initial HTTP headers.
736
	// @Param body the initial HTTP body.
737
	// @Param endOfStream whether this is the end of the stream.
738
	// @Param timeoutMs the timeout in milliseconds.
739
	// @Param callback the callback interface to handle the stream events.
740
	// @Return the result of the HTTP stream initialization and the stream ID.
741
	StartHttpStream(cluster string, headers [][2]string, body []byte, endOfStream bool,
742
		timeoutMs uint64, cb HttpStreamCallback) (HttpCalloutInitResult, uint64)
743

            
744
	// SendHttpStreamData sends data on an existing HTTP stream started via StartHttpStream.
745
	// @Param streamID the ID of the HTTP stream.
746
	// @Param body the HTTP body to be sent.
747
	// @Param endOfStream whether this is the end of the stream.
748
	// @Return whether the data was successfully sent.
749
	SendHttpStreamData(streamID uint64, body []byte, endOfStream bool) bool
750

            
751
	// SendHttpStreamTrailers sends trailers on an existing HTTP stream started via StartHttpStream.
752
	// @Param streamID the ID of the HTTP stream.
753
	// @Param trailers the HTTP trailers to be sent.
754
	// @Return whether the trailers were successfully sent.
755
	SendHttpStreamTrailers(streamID uint64, trailers [][2]string) bool
756

            
757
	// ResetHttpStream resets an existing HTTP stream started via StartHttpStream.
758
	// @Param streamID the ID of the HTTP stream.
759
	ResetHttpStream(streamID uint64)
760

            
761
	// GetScheduler retrieves a scheduler for deferred task execution in the config context.
762
	// This should be called only during the plugin configuration phase, and the returned
763
	// Scheduler can be used later even outside of the callbacks and at other threads.
764
	GetScheduler() Scheduler
765
}