master
go 75 lines 2.21 KB
Raw
1 // SPDX-License-Identifier: GPL-3.0-or-later
2
3 package funcapi
4
5 import (
6 "context"
7 "fmt"
8 )
9
10 // MethodHandler defines the interface for handling method requests.
11 // Methods are defined in Creator.Methods(); this interface handles the requests.
12 //
13 // Example implementation:
14 //
15 // type funcTopQueries struct {
16 // db *sql.DB
17 // }
18 //
19 // func (f *funcTopQueries) MethodParams(ctx context.Context, method string) ([]ParamConfig, error) {
20 // return nil, nil // or return dynamic params from database
21 // }
22 //
23 // func (f *funcTopQueries) Handle(ctx context.Context, method string, params ResolvedParams) *FunctionResponse {
24 // // query database and build response
25 // }
26 type MethodHandler interface {
27 // MethodParams returns dynamic params for a method.
28 // Return nil to use static params from MethodConfig.RequiredParams.
29 // The context should be used for timeout/cancellation of database queries.
30 MethodParams(ctx context.Context, method string) ([]ParamConfig, error)
31
32 // Handle processes a method request and returns the response.
33 // The context should be used for timeout/cancellation of database queries.
34 Handle(ctx context.Context, method string, params ResolvedParams) *FunctionResponse
35
36 // Cleanup releases any resources held by the handler.
37 // Called when the collector is being stopped.
38 Cleanup(ctx context.Context)
39 }
40
41 // ErrorResponse creates an error FunctionResponse.
42 func ErrorResponse(status int, format string, args ...any) *FunctionResponse {
43 msg := format
44 if len(args) > 0 {
45 msg = fmt.Sprintf(format, args...)
46 }
47 return &FunctionResponse{
48 Status: status,
49 Message: msg,
50 }
51 }
52
53 // NotFoundResponse returns a 404 response for unknown methods.
54 func NotFoundResponse(method string) *FunctionResponse {
55 return &FunctionResponse{
56 Status: 404,
57 Message: "unknown method: " + method,
58 }
59 }
60
61 // UnavailableResponse returns a 503 response when data is not yet available.
62 func UnavailableResponse(msg string) *FunctionResponse {
63 return &FunctionResponse{
64 Status: 503,
65 Message: msg,
66 }
67 }
68
69 // InternalErrorResponse returns a 500 response for internal errors.
70 func InternalErrorResponse(format string, args ...any) *FunctionResponse {
71 return &FunctionResponse{
72 Status: 500,
73 Message: fmt.Sprintf(format, args...),
74 }
75 }