-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
236 lines (199 loc) · 7.5 KB
/
main.go
File metadata and controls
236 lines (199 loc) · 7.5 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
package main
import (
"context"
"fmt"
"log"
"time"
"github.com/eryph-org/go-client/compute"
"github.com/eryph-org/go-client/compute_api"
"github.com/eryph-org/go-client/runtime"
"github.com/eryph-org/go-client/runtime/config"
"github.com/eryph-org/go-client/runtime/environment"
)
// BasicAuthExample demonstrates authentication and the executor pattern
func main() {
fmt.Println("Eryph Go Client - Basic Authentication Example")
fmt.Println("============================================")
// Step 1: Demonstrate credential discovery
fmt.Println("\n🔍 Step 1: Discovering credentials...")
env := environment.NewDefaultEnvironment()
logger := &consoleLogger{}
lookup := config.NewClientCredentialsLookup(env, logger)
creds := lookup.FindCredentials()
if creds == nil {
fmt.Println("❌ No credentials found!")
fmt.Println("\nTo run this example, you need:")
fmt.Println("1. eryph-zero running (for system client)")
fmt.Println("2. OR configured client credentials in:")
fmt.Println(" - ./.eryph/default.config")
fmt.Println(" - ~/.config/eryph/default.config (Linux/macOS)")
fmt.Println(" - %APPDATA%\\eryph\\default.config (Windows)")
return
}
fmt.Printf("✅ Found credentials: %s (config: %s)\n", creds.ID, creds.Configuration)
fmt.Printf(" Identity Provider: %s\n", creds.IdentityProvider.String())
// Step 2: Create executor for high-level operations
fmt.Println("\n🔧 Step 2: Creating compute executor...")
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
executor := compute.NewExecutor()
fmt.Println("✅ Compute executor created")
// Step 3: Test authentication using executor pattern
fmt.Println("\n🌐 Step 3: Testing API connectivity with executor...")
// Define client options for read operations
readOptions := &runtime.ClientOptions{
Scopes: []string{"compute:read"},
}
// Test project listing using executor
fmt.Println("\nTesting project listing with executor...")
projects, err := compute.ExecuteListWithType(
executor,
ctx,
readOptions,
func(ctx context.Context, client compute.ClientInterface) ([]compute_api.Project, error) {
resp, err := client.API().ProjectsListWithResponse(ctx, nil)
if err != nil {
return nil, err
}
if resp.StatusCode() != 200 {
return nil, fmt.Errorf("API returned status %d: %s", resp.StatusCode(), string(resp.Body))
}
return resp.JSON200.Value, nil
},
)
if err != nil {
fmt.Printf("❌ Project listing failed: %v\n", err)
} else {
fmt.Printf("✅ Successfully listed %d projects using executor\n", len(projects))
// Show first few projects
for i, project := range projects {
if i >= 3 {
fmt.Printf(" ... and %d more\n", len(projects)-3)
break
}
fmt.Printf(" - %s (%s)\n", project.Name, project.Id)
}
}
// Test catlet listing using executor
fmt.Println("\nTesting catlet listing with executor...")
catlets, err := compute.ExecuteListWithType(
executor,
ctx,
readOptions,
func(ctx context.Context, client compute.ClientInterface) ([]compute_api.Catlet, error) {
resp, err := client.API().CatletsListWithResponse(ctx, nil)
if err != nil {
return nil, err
}
if resp.StatusCode() != 200 {
return nil, fmt.Errorf("API returned status %d: %s", resp.StatusCode(), string(resp.Body))
}
return resp.JSON200.Value, nil
},
)
if err != nil {
fmt.Printf("❌ Catlet listing failed: %v\n", err)
} else {
fmt.Printf("✅ Successfully listed %d catlets using executor\n", len(catlets))
// Show catlet details
for i, catlet := range catlets {
if i >= 3 {
fmt.Printf(" ... and %d more\n", len(catlets)-3)
break
}
status := "Unknown"
if catlet.Status != nil {
status = string(*catlet.Status)
}
fmt.Printf(" - %s (%s): %s\n", catlet.Name, catlet.Id, status)
}
}
// Step 4: Demonstrate endpoint discovery
fmt.Println("\n🔗 Step 4: Endpoint discovery...")
endpointLookup := config.NewEndpointLookup(env, logger)
// Show available endpoints
identityEndpoint := endpointLookup.GetEndpoint(config.EndpointIdentity, creds.Configuration)
computeEndpoint := endpointLookup.GetEndpoint(config.EndpointCompute, creds.Configuration)
fmt.Printf("Available endpoints for configuration '%s':\n", creds.Configuration)
if identityEndpoint != nil {
fmt.Printf(" - Identity: %s\n", identityEndpoint.String())
}
if computeEndpoint != nil {
fmt.Printf(" - Compute: %s\n", computeEndpoint.String())
}
// Step 5: Demonstrate different authentication scenarios with executor
fmt.Println("\n🎯 Step 5: Authentication scenarios with executor...")
// Test with specific configuration
specificOptions := &runtime.ClientOptions{
ConfigName: creds.Configuration, // Use discovered config explicitly
Scopes: []string{"compute:read"},
}
// Test using raw executor call
result, err := executor.Call(
ctx,
specificOptions,
func(ctx context.Context, client compute.ClientInterface) (interface{}, error) {
// Just test that we can create a client successfully
return fmt.Sprintf("Successfully connected to %s", creds.Configuration), nil
},
)
if err != nil {
fmt.Printf("❌ Failed to use specific config: %v\n", err)
} else {
fmt.Printf("✅ %s\n", result)
}
// Test error handling with invalid scopes
fmt.Println("\nTesting error handling with invalid scopes...")
invalidOptions := &runtime.ClientOptions{
Scopes: []string{"invalid:scope"},
}
_, err = executor.Call(
ctx,
invalidOptions,
func(ctx context.Context, client compute.ClientInterface) (interface{}, error) {
return "Should not reach here", nil
},
)
if err != nil {
fmt.Printf("✅ Properly handled invalid scope error: %v\n", err)
} else {
fmt.Println("⚠️ Invalid scope was unexpectedly accepted")
}
// Step 6: Demonstrate operation manager setup
fmt.Println("\n⚙️ Step 6: Operation management setup...")
// Get a client for operation tracking
client, err := executor.GetClient(ctx, readOptions)
if err != nil {
fmt.Printf("❌ Failed to get client for operations: %v\n", err)
} else {
manager := compute.NewOperationManager(client)
fmt.Printf("✅ Operation manager created and ready for async operations\n")
fmt.Printf(" Manager can track operations using: manager.NewOperationTracker(operationID)\n")
_ = manager // Use variable to avoid unused warning
}
fmt.Println("\n🎉 Basic authentication example completed successfully!")
fmt.Println("\nWhat you learned:")
fmt.Println("- How to discover credentials automatically")
fmt.Println("- How to use the executor pattern for API calls")
fmt.Println("- How to handle different authentication scenarios")
fmt.Println("- How to set up operation managers for async tasks")
fmt.Println("\nNext steps:")
fmt.Println("- Try examples/create_catlet/ to see async operations")
fmt.Println("- Try examples/list_resources/ for advanced querying patterns")
fmt.Println("- Check the documentation at docs.eryph.io")
}
// consoleLogger implements config.Logger for console output
type consoleLogger struct{}
func (l *consoleLogger) Debug(msg string, keysAndValues ...interface{}) {
// Uncomment to see debug logs:
// fmt.Printf("DEBUG: %s %v\n", msg, keysAndValues)
}
func (l *consoleLogger) Info(msg string, keysAndValues ...interface{}) {
fmt.Printf("INFO: %s %v\n", msg, keysAndValues)
}
func (l *consoleLogger) Warn(msg string, keysAndValues ...interface{}) {
fmt.Printf("WARN: %s %v\n", msg, keysAndValues)
}
func (l *consoleLogger) Error(msg string, keysAndValues ...interface{}) {
fmt.Printf("ERROR: %s %v\n", msg, keysAndValues)
}