### Go SDK Configuration Example Source: https://github.com/nebius/gosdk/blob/main/_autodocs/configuration.md A comprehensive example demonstrating how to configure the Nebius Go SDK with credentials, logging, timeouts, user agent, parent ID, and domain. ```go package main import ( "context" "fmt" "os" "time" "log/slog" "github.com/nebius/gosdk" "github.com/nebius/gosdk/auth" ) func main() { ctx := context.Background() // Configure SDK comprehensively sdk, err := gosdk.New( ctx, // Credentials gosdk.WithCredentials( gosdk.ServiceAccountReader( auth.NewServiceAccountCredentialsFileParser( nil, "~/.config/nebius/sa.json", ), ), ), // Logging gosdk.WithLogger( slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{ Level: slog.LevelDebug, })), ), // Timeouts gosdk.WithTimeout(2 * time.Minute), gosdk.WithAuthTimeout(10 * time.Minute), // Identification gosdk.WithUserAgentPrefix("my-app/1.0"), // Defaults gosdk.WithParentID("project-123"), // Endpoint gosdk.WithDomain("api.nebius.cloud"), ) if err != nil { fmt.Fprintf(os.Stderr, "Failed to create SDK: %v\n", err) os.Exit(1) } defer sdk.Close() // Use SDK... } ``` -------------------------------- ### Run Example Tests Source: https://github.com/nebius/gosdk/blob/main/_autodocs/api-reference/utilities.md Command to run all example tests included with the SDK, useful for verifying common usage patterns. ```bash go test -run Example ``` -------------------------------- ### Install Nebius AI Cloud SDK for Go Source: https://github.com/nebius/gosdk/blob/main/README.md Add the SDK to your Go project. Use 'go get -u' to update to the latest version. ```bash go get github.com/nebius/gosdk ``` ```bash go get -u github.com/nebius/gosdk ``` -------------------------------- ### Wait for Operation Completion Example Source: https://github.com/nebius/gosdk/blob/main/_autodocs/api-reference/operations.md Example demonstrating how to initiate an operation and then wait for its completion using the Wait method. The operation object returned by instanceService.Create is already wrapped. ```go operation, err := instanceService.Create(ctx, request) if err != nil { return err } // operation is already wrapped; no need to call operations.New() operation, err = operation.Wait(ctx) if err != nil { return err } ``` -------------------------------- ### Verify Nebius Go SDK Installation Source: https://github.com/nebius/gosdk/blob/main/_autodocs/api-reference/utilities.md Run this command to execute the SDK's test suite and verify a successful installation. This ensures all components are working as expected. ```bash go test github.com/nebius/gosdk/... ``` -------------------------------- ### Service Accessor Method Example Source: https://github.com/nebius/gosdk/blob/main/_autodocs/types.md Example of a service accessor method within the `Services` struct. These methods return specific service clients. ```go func (s Services) ServiceName() serviceNamePackage.ServiceName { // ... implementation } ``` -------------------------------- ### Use NewCompleted Example Source: https://github.com/nebius/gosdk/blob/main/_autodocs/api-reference/operations.md Example of using NewCompleted to create an operation wrapper from a pre-completed operation message and accessing its ID. ```go // Only valid for completed operations operation, err := operations.NewCompleted(completedOp) if err != nil { return err } log.Println(operation.ID()) ``` -------------------------------- ### Initialize SDK and Manage Compute Instances Source: https://github.com/nebius/gosdk/blob/main/README.md Demonstrates initializing the SDK with IAM token authorization and performing CRUD operations on compute instances. Includes creating, getting, updating, and deleting instances, as well as waiting for operations to complete. ```go package example import ( "context" "fmt" "os" "github.com/nebius/gosdk" common "github.com/nebius/gosdk/proto/nebius/common/v1" compute "github.com/nebius/gosdk/proto/nebius/compute/v1" ) func Example() error { ctx := context.Background() // Initialize SDK with IAM token sdk, err := gosdk.New( ctx, gosdk.WithCredentials( gosdk.IAMToken(os.Getenv("IAM_TOKEN")), ), ) if err != nil { return fmt.Errorf("create gosdk: %w", err) } defer sdk.Close() instanceService := sdk.Services().Compute().V1().Instance() // Create resource operation, err := instanceService.Create(ctx, &compute.CreateInstanceRequest{ Metadata: &common.ResourceMetadata{ ParentId: "my-project-id", Name: "my-instance", }, Spec: &compute.InstanceSpec{ // configuration }, }) if err != nil { return fmt.Errorf("create instance: %w", err) } // Wait for the create operation to complete successfully operation, err = operation.Wait(ctx) if err != nil { return fmt.Errorf("wait for instance creation: %w", err) } instanceID := operation.ResourceID() // Get resource by ID instance, err := instanceService.Get(ctx, &compute.GetInstanceRequest{ Id: instanceID, }) if err != nil { return fmt.Errorf("get instance: %w", err) } // Get resource by name instance, err = instanceService.GetByName(ctx, &common.GetByNameRequest{ ParentId: "my-project-id", Name: "my-instance", }) if err != nil { return fmt.Errorf("get instance by name: %w", err) } // Update resource operation, err = instanceService.Update(ctx, &compute.UpdateInstanceRequest{ Metadata: &common.ResourceMetadata{ Id: instanceID, ParentId: "my-project-id", Name: "my-instance", }, Spec: &compute.InstanceSpec{ // updated configuration }, }) if err != nil { return fmt.Errorf("update instance: %w", err) } // Wait for update operation complete successfully operation, err = operation.Wait(ctx) if err != nil { return fmt.Errorf("wait for instance update: %w", err) } // Iterate over all resources inside container req := &compute.ListInstancesRequest{ParentId: "my-project-id"} for instance, err = range instanceService.Filter(ctx, req) { if err != nil { return fmt.Errorf("list instances: %w", err) } if instance.GetMetadata().GetId() == instanceID { continue // skip just created instance } // Delete resource operation, err = instanceService.Delete(ctx, &compute.DeleteInstanceRequest{ Id: instance.GetMetadata().GetId(), }) if err != nil { return fmt.Errorf("delete instance: %w", err) } // Wait for delete operation complete successfully operation, err = operation.Wait(ctx) if err != nil { return fmt.Errorf("wait for instance delete: %w", err) } } return nil } ``` -------------------------------- ### Poll Operation Status Example Source: https://github.com/nebius/gosdk/blob/main/_autodocs/api-reference/operations.md Example of polling an operation's status once and checking if it has completed. ```go // Check status once operation, err := operation.Poll(ctx) if err != nil { return err } if operation.Done() { log.Println("Operation completed") } ``` -------------------------------- ### Install Nebius Go SDK Source: https://github.com/nebius/gosdk/blob/main/_autodocs/api-reference/utilities.md Use this command to fetch the Nebius Go SDK package. Ensure your Go version meets the minimum requirements. ```bash go get github.com/nebius/gosdk ``` -------------------------------- ### Example: Using OneOfCredentials with Selectors Source: https://github.com/nebius/gosdk/blob/main/_autodocs/api-reference/auth.md Demonstrates how to configure multiple credentials using named selectors and then use a specific selector for a request. ```go sdk, err := gosdk.New( ctx, gosdk.WithCredentials( gosdk.OneOfCredentials(map[auth.Selector]gosdk.Credentials{ auth.Select("user"): gosdk.IAMToken(userToken), auth.Select("admin"): gosdk.IAMToken(adminToken), }), ), ) // Use selector in requests list, err := service.List( ctx, request, auth.Select("admin"), ) ``` -------------------------------- ### SDK Initialization Source: https://github.com/nebius/gosdk/blob/main/_autodocs/README.md Guides users on how to initialize the Nebius Go SDK. This involves creating a new SDK instance, choosing appropriate credential types, and configuring various SDK options. ```APIDOC ## SDK Initialization ### Description This section details the process of initializing the Nebius Go SDK. It covers the `New()` constructor for the SDK and guides users through selecting and configuring credentials and other SDK options. ### Methods - **New()**: Initializes the SDK. ### Related Files - `api-reference/sdk.md`: SDK constructor and initialization. - `api-reference/credentials.md`: Information on credential types. - `configuration.md`: Details on all SDK options. ``` -------------------------------- ### Example: Disabling Authentication for a Request Source: https://github.com/nebius/gosdk/blob/main/_autodocs/api-reference/auth.md Shows how to use the `auth.Disable()` option to make a request without authentication. ```go // Make a request without authentication even if credentials are configured response, err := service.Get( ctx, request, auth.Disable(), ) ``` -------------------------------- ### Import Proto Definitions Source: https://github.com/nebius/gosdk/blob/main/_autodocs/api-reference/utilities.md Illustrates the import pattern for generated protobuf code for Nebius API messages, showing examples for compute, common, and iam services. ```go import " "github.com/nebius/gosdk/proto/nebius//v" // Examples: import compute "github.com/nebius/gosdk/proto/nebius/compute/v1" import common "github.com/nebius/gosdk/proto/nebius/common/v1" import iam "github.com/nebius/gosdk/proto/nebius/iam/v1" ``` -------------------------------- ### Get Instance by Name Source: https://github.com/nebius/gosdk/blob/main/README.md Retrieves a compute instance by its name and parent project ID. ```APIDOC ## Get Instance by Name ### Description Retrieves a compute instance by its name and parent project ID. ### Method `GetByName` ### Endpoint `/v1/compute/instances` (gRPC) ### Parameters #### Query Parameters - **ParentId** (string) - Required - The ID of the parent project. - **Name** (string) - Required - The name of the instance. ### Request Example ```go instance, err = instanceService.GetByName(ctx, &common.GetByNameRequest{ ParentId: "my-project-id", Name: "my-instance", }) ``` ### Response #### Success Response (200) Returns a `compute.Instance` object representing the instance. #### Response Example ```go // instance object details ``` -------------------------------- ### BearerToken Usage Example Source: https://github.com/nebius/gosdk/blob/main/_autodocs/api-reference/auth.md Demonstrates how to obtain and check the expiration of a bearer token. Ensure you have a valid context and handle potential errors during token retrieval. ```Go token, err := sdk.BearerToken(ctx) if err != nil { return err } if token.IsExpired() { log.Println("Token has expired") } else if !token.Empty() { log.Printf("Token expires at: %v", token.ExpiresAt) } ``` -------------------------------- ### Go SDK Get Resource By Name Operation Source: https://github.com/nebius/gosdk/blob/main/_autodocs/api-reference/services.md Retrieves a resource by its name within a specified parent container. ```go instance, err := service.GetByName(ctx, &common.GetByNameRequest{ ParentId: parentID, Name: "instance-name", }) if err != nil { return err } ``` -------------------------------- ### Start Docker Development Shell Source: https://github.com/nebius/gosdk/blob/main/CONTRIBUTING.md Access a shell session within the project's Docker development environment. This is useful for consistent development and testing. ```bash make bash ``` -------------------------------- ### Standard Go SDK Imports Source: https://github.com/nebius/gosdk/blob/main/_autodocs/types.md These are the common imports needed when using the Nebius Go SDK. Ensure these packages are installed in your Go environment. ```go import ( "context" "time" "github.com/nebius/gosdk" "github.com/nebius/gosdk/auth" "github.com/nebius/gosdk/operations" common "github.com/nebius/gosdk/proto/nebius/common/v1" compute "github.com/nebius/gosdk/proto/nebius/compute/v1" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" ) ``` -------------------------------- ### Get Compute Instance by Name Source: https://github.com/nebius/gosdk/blob/main/README.md Retrieves a compute instance by its name and parent project ID. This is an alternative to fetching by ID. ```go instance, err = instanceService.GetByName(ctx, &common.GetByNameRequest{ ParentId: "my-project-id", Name: "my-instance", }) if err != nil { return fmt.Errorf("get instance by name: %w", err) } ``` -------------------------------- ### Go SDK Get Resource Operation Source: https://github.com/nebius/gosdk/blob/main/_autodocs/api-reference/services.md Retrieves a resource by its ID using the service's Get method. ```go instance, err := service.Get(ctx, &compute.GetInstanceRequest{ Id: resourceID, }) if err != nil { return err } ``` -------------------------------- ### Initialize SDK with Provided Private Key Content Source: https://github.com/nebius/gosdk/blob/main/README.md Initializes the SDK by providing the private key content directly, along with the public key ID and service account ID. This method is useful when the private key is available as a string or byte slice. ```go import "github.com/nebius/gosdk/auth" privateKey, _ := os.ReadFile("path/to/private_key.pem") auth.NewPrivateKeyParser( privateKey, "public-key-id", "service-account-id", ) ``` -------------------------------- ### Customize gRPC Logging Events Source: https://github.com/nebius/gosdk/blob/main/SCENARIOS.md Configure the SDK to log specific gRPC events like call start, finish, and payload transmission. This requires a logger to be set. ```go import "github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/logging" sdk, err := gosdk.New( ctx, gosdk.WithLogger(logger), gosdk.WithLoggingOptions( logging.WithLogOnEvents( logging.StartCall, logging.FinishCall, logging.PayloadReceived, logging.PayloadSent, ), ), ) ``` -------------------------------- ### Initialize Nebius Go SDK Source: https://github.com/nebius/gosdk/blob/main/_autodocs/INDEX.md Demonstrates how to create and initialize the Nebius Go SDK using IAM token credentials. Ensure to handle potential errors during initialization and defer closing the SDK client. ```go import "github.com/nebius/gosdk" // Create and initialize SDK ctx := context.Background() sdk, err := gosdk.New( ctx, gosdk.WithCredentials(gosdk.IAMToken(token)), ) if err != nil { return err } defer sdk.Close() // Access services via fluent interface instanceService := sdk.Services().Compute().V1().Instance() // Perform operations operation, err := instanceService.Create(ctx, request) if err != nil { return err } // Wait for async operation operation, err = operation.Wait(ctx) if err != nil { return err } ``` -------------------------------- ### SDK Initialization with Metrics and Auth Options Source: https://github.com/nebius/gosdk/blob/main/_autodocs/api-reference/auth.md Configures the SDK with both custom authentication metrics and logger options during initialization. ```go sdk, err := gosdk.New( ctx, gosdk.WithCredentials( gosdk.ServiceAccountReader(reader), ), gosdk.WithAuthMetrics(metricsRecorder), gosdk.WithAuthOptions( auth.WithLogger(logger), ), ) ``` -------------------------------- ### Implement Retry Logic in Go Source: https://github.com/nebius/gosdk/blob/main/_autodocs/errors.md Implement a basic retry mechanism for operations that might fail with transient errors like 'Unavailable'. This example retries up to 3 times with increasing delays. ```go var instance *compute.Instance var err error for attempt := 0; attempt < 3; attempt++ { instance, err = service.Get(ctx, request) if err == nil { break } // Check if error is retryable var svcErr *serviceerror.Error if errors.As(err, &svcErr) { // Extract status code to determine if retryable if code := status.Code(svcErr.Wrapped); code == codes.Unavailable { time.Sleep(time.Duration(attempt) * time.Second) continue } } return err } ``` -------------------------------- ### SDK Initialization with Service Account File Source: https://github.com/nebius/gosdk/blob/main/_autodocs/api-reference/auth.md Initializes the SDK using credentials from a service account JSON file. Supports custom file paths. ```go sdk, err := gosdk.New( ctx, gosdk.WithCredentials( gosdk.ServiceAccountReader( auth.NewServiceAccountCredentialsFileParser( nil, "~/.config/nebius/sa.json", ), ), ), ) ``` -------------------------------- ### Get Instance Source: https://github.com/nebius/gosdk/blob/main/README.md Retrieves a compute instance by its ID. The operation object itself does not contain the resource state; a separate `Get` call is needed after the operation completes. ```APIDOC ## Get Instance ### Description Retrieves a compute instance by its ID. The operation object itself does not contain the resource state; a separate `Get` call is needed after the operation completes. ### Method `Get` ### Endpoint `/v1/compute/instances/{id}` (gRPC) ### Parameters #### Path Parameters - **Id** (string) - Required - The unique identifier of the instance. ### Request Example ```go instance, err := instanceService.Get(ctx, &compute.GetInstanceRequest{ Id: instanceID, }) ``` ### Response #### Success Response (200) Returns a `compute.Instance` object representing the instance. #### Response Example ```go // instance object details ``` -------------------------------- ### Typical Operation Workflow Source: https://github.com/nebius/gosdk/blob/main/_autodocs/api-reference/operations.md Demonstrates the standard sequence for creating a resource, waiting for its operation to complete, and then fetching the created resource using the Nebius Go SDK. ```go import ( "context" "fmt" compute "github.com/nebius/gosdk/proto/nebius/compute/v1" ) // 1. Create a resource (returns Operation) operation, err := instanceService.Create(ctx, &compute.CreateInstanceRequest{ // ... }) if err != nil { return fmt.Errorf("create request failed: %w", err) } // 2. Wait for completion operation, err = operation.Wait(ctx) if err != nil { return fmt.Errorf("operation failed: %w", err) } // 3. Extract the resource ID resourceID := operation.ResourceID() // 4. Fetch the created resource if needed resource, err := instanceService.Get(ctx, &compute.GetInstanceRequest{ Id: resourceID, }) if err != nil { return fmt.Errorf("get resource failed: %w", err) } ``` -------------------------------- ### Initialize SDK with Service Account Credentials File Source: https://github.com/nebius/gosdk/blob/main/README.md Recommended for server-to-server communication. Initializes the SDK using a service account JSON credentials file. The SDK handles token generation and background refresh. ```go import "github.com/nebius/gosdk/auth" sdk, err := gosdk.New( ctx, gosdk.WithCredentials( gosdk.ServiceAccountReader( auth.NewServiceAccountCredentialsFileParser( nil, // nil to use the real file system "~/path/to/service_account.json", ), ), ), ) ``` -------------------------------- ### Initialize SDK with Auth Metrics Source: https://github.com/nebius/gosdk/blob/main/_autodocs/api-reference/utilities.md Demonstrates how to initialize the Nebius SDK with a custom metrics recorder for authentication events. ```go sdk, err := gosdk.New( ctx, gosdk.WithAuthMetrics(metricsRecorder), ) ``` -------------------------------- ### Get Operation Description Source: https://github.com/nebius/gosdk/blob/main/_autodocs/api-reference/operations.md Retrieves a human-readable description of the operation. ```APIDOC ## Get Operation Description ### Description Returns a human-readable description of the operation. ### Method `Description` ### Parameters: None ### Returns: - `string` — Operation description (e.g., "Creating instance") ``` -------------------------------- ### Create SDK with PrivateKeyFileParser Source: https://github.com/nebius/gosdk/blob/main/_autodocs/api-reference/auth.md Use PrivateKeyFileParser to initialize the SDK with credentials from a PEM file. The 'fs' parameter can be nil to use the real file system. ```go reader := auth.NewPrivateKeyFileParser( nil, "~/.config/nebius/sa.pem", "key-id", "serviceaccount-.", ) ctx := context.Background() sdk, err := gosdk.New( ctx, gosdk.WithCredentials(gosdk.ServiceAccountReader(reader)), ) ``` -------------------------------- ### Initialize SDK with PEM Encoded Private Key File Source: https://github.com/nebius/gosdk/blob/main/README.md Initializes the SDK using a PEM-encoded private key file, public key ID, and service account ID. This is an alternative to using a JSON credentials file for service account authorization. ```go import "github.com/nebius/gosdk/auth" auth.NewPrivateKeyFileParser( nil, // nil to use the real file system "~/path/to/private_key.pem", "public-key-id", "service-account-id", ) ``` -------------------------------- ### Get Operation ID Source: https://github.com/nebius/gosdk/blob/main/_autodocs/api-reference/operations.md Returns the unique identifier for the operation. ```APIDOC ## Get Operation ID ### Description Returns the unique operation ID. ### Method `ID` ### Parameters: None ### Returns: - `string` — Operation identifier ``` -------------------------------- ### SDK Initialization with Static Token Source: https://github.com/nebius/gosdk/blob/main/_autodocs/api-reference/auth.md Initializes the SDK using a static IAM token obtained from an environment variable. ```go import "github.com/nebius/gosdk/auth" sdk, err := gosdk.New( ctx, gosdk.WithCredentials(gosdk.IAMToken(os.Getenv("IAM_TOKEN"))), ) ``` -------------------------------- ### Get Operation ID Source: https://github.com/nebius/gosdk/blob/main/_autodocs/api-reference/operations.md Returns the unique identifier for an operation. ```go func (o Operation) ID() string { // ... implementation details ... } ``` -------------------------------- ### Get Request Headers Source: https://github.com/nebius/gosdk/blob/main/_autodocs/api-reference/operations.md Retrieves the HTTP headers from the original request. ```APIDOC ## Get Request Headers ### Description Returns HTTP headers from the original request. ### Method `RequestHeaders` ### Parameters: None ### Returns: - `http.Header` — Request headers as a copy; safe to modify ``` -------------------------------- ### Get Progress Data Source: https://github.com/nebius/gosdk/blob/main/_autodocs/api-reference/operations.md Retrieves additional progress information for a running operation. ```APIDOC ## Get Progress Data ### Description Returns additional progress information while the operation is running, or nil if not available. ### Method `ProgressData` ### Parameters: None ### Returns: - `proto.Message` — Progress data message; nil if not present or empty ``` -------------------------------- ### Create Compute Instance and Wait for Operation Source: https://github.com/nebius/gosdk/blob/main/README.md Demonstrates creating a compute instance and using the `Wait` method to confirm the operation's completion. Ensure necessary imports are included. ```go import common "github.com/nebius/gosdk/proto/nebius/common/v1" import compute "github.com/nebius/gosdk/proto/nebius/compute/v1" instanceService := sdk.Services().Compute().V1().Instance() operation, err := instanceService.Create(ctx, &compute.CreateInstanceRequest{ Metadata: &common.ResourceMetadata{ ParentId: "my-project-id", Name: "my-instance", }, Spec: &compute.InstanceSpec{ // instance configuration }, }) if err != nil { return fmt.Errorf("create instance: %w", err) } operation, err = operation.Wait(ctx) if err != nil { return fmt.Errorf("wait for instance create: %w", err) } instanceID := operation.ResourceID() ``` -------------------------------- ### Get Original Request Source: https://github.com/nebius/gosdk/blob/main/_autodocs/api-reference/operations.md Retrieves the original request message that initiated the operation. ```APIDOC ## Get Original Request ### Description Returns the original request that initiated the operation. ### Method `Request` ### Parameters: None ### Returns: - `proto.Message` — Original request message; may be nil if not available ``` -------------------------------- ### Initialize SDK with Context Source: https://github.com/nebius/gosdk/blob/main/README.md Initialize the SDK with a context. Ensure to call Close() for resource cleanup. Additional options can be passed to the constructor. ```go import "github.com/nebius/gosdk" ctx := context.Background() sdk, err := gosdk.New(ctx /*, option1, option2, option3 */) if err != nil { return fmt.Errorf("create gosdk: %w", err) } deffer sdk.Close() ``` -------------------------------- ### Get Operation Creation Timestamp Source: https://github.com/nebius/gosdk/blob/main/_autodocs/api-reference/operations.md Returns the timestamp indicating when the operation was created. ```APIDOC ## Get Operation Creation Timestamp ### Description Returns the timestamp when the operation was created. ### Method `CreatedAt` ### Parameters: None ### Returns: - `time.Time` — Creation timestamp ``` -------------------------------- ### Get Operation Creation Timestamp Source: https://github.com/nebius/gosdk/blob/main/_autodocs/api-reference/operations.md Returns the timestamp indicating when the operation was initiated. ```go func (o Operation) CreatedAt() time.Time { // ... implementation details ... } ``` -------------------------------- ### Get Operation Description Source: https://github.com/nebius/gosdk/blob/main/_autodocs/api-reference/operations.md Retrieves a human-readable description of the operation's purpose. ```go func (o Operation) Description() string { // ... implementation details ... } ``` -------------------------------- ### Get Tenant ID Source: https://github.com/nebius/gosdk/blob/main/_autodocs/api-reference/sdk.md Retrieves the configured tenant ID for the SDK instance. ```APIDOC ## SDK TenantID ### Description Returns the tenant ID configured in the SDK, if any. Used for operations that require a tenant as the parent ID. ### Signature `func (s *SDK) TenantID() string` ### Parameters None ### Returns - `string` - Tenant ID set via `WithTenantID()` or from the config reader; empty if not set ``` -------------------------------- ### Create SDK with PrivateKeyParser Source: https://github.com/nebius/gosdk/blob/main/_autodocs/api-reference/auth.md Use PrivateKeyParser to initialize the SDK with credentials from PEM-encoded private key bytes. Ensure the keyBytes are correctly read from a file. ```go keyBytes, _ := os.ReadFile("~/.config/nebius/key.pem") reader := auth.NewPrivateKeyParser(keyBytes, "key-id", "sa-id") ctx := context.Background() sdk, err := gosdk.New( ctx, gosdk.WithCredentials(gosdk.ServiceAccountReader(reader)), ) ``` -------------------------------- ### Get Progress Tracker Source: https://github.com/nebius/gosdk/blob/main/_autodocs/api-reference/operations.md Provides access to progress tracking information for operations that support it. ```APIDOC ## Get Progress Tracker ### Description Returns progress tracking information if the operation supports progress reporting. ### Method `ProgressTracker` ### Parameters: None ### Returns: - `OperationProgressTracker` — Progress tracker interface; provides progress details ``` -------------------------------- ### Complete Compute Instance Workflow in Go Source: https://github.com/nebius/gosdk/blob/main/_autodocs/api-reference/services.md This Go code demonstrates a full workflow for managing a compute instance using the Nebius SDK. It covers creating an instance, waiting for its creation, retrieving its details, and finally deleting it. Ensure you have the necessary credentials and project ID configured. ```go package main import ( "context" "fmt" "github.com/nebius/gosdk" common "github.com/nebius/gosdk/proto/nebius/common/v1" compute "github.com/nebius/gosdk/proto/nebius/compute/v1" ) func main() { ctx := context.Background() // Initialize SDK sdk, err := gosdk.New(ctx, gosdk.WithCredentials(gosdk.IAMToken(token))) if err != nil { panic(err) } defer sdk.Close() // Access Compute service instances := sdk.Services().Compute().V1().Instance() // Create instance createOp, err := instances.Create(ctx, &compute.CreateInstanceRequest{ Metadata: &common.ResourceMetadata{ ParentId: projectID, Name: "my-instance", }, Spec: &compute.InstanceSpec{ // configuration... }, }) if err != nil { panic(err) } // Wait for creation createOp, err = createOp.Wait(ctx) if err != nil { panic(err) } instanceID := createOp.ResourceID() fmt.Printf("Created instance: %s\n", instanceID) // Get instance instance, err := instances.Get(ctx, &compute.GetInstanceRequest{ Id: instanceID, }) if err != nil { panic(err) } fmt.Printf("Instance name: %s\n", instance.Metadata.Name) // Delete instance deleteOp, err := instances.Delete(ctx, &compute.DeleteInstanceRequest{ Id: instanceID, }) if err != nil { panic(err) } deleteOp, err = deleteOp.Wait(ctx) if err != nil { panic(err) } fmt.Println("Instance deleted") } ``` -------------------------------- ### Initialize SDK with IAM Token Source: https://github.com/nebius/gosdk/blob/main/README.md Initialize the SDK using an IAM token obtained from an environment variable. This method is suitable for testing but requires manual token refreshes for production. ```go token := os.Getenv("IAM_TOKEN") sdk, err := gosdk.New( ctx, gosdk.WithCredentials( gosdk.IAMToken(token), ), ) ``` -------------------------------- ### Get Operation Creator ID Source: https://github.com/nebius/gosdk/blob/main/_autodocs/api-reference/operations.md Returns the identifier of the user or service that initiated the operation. ```APIDOC ## Get Operation Creator ID ### Description Returns the ID of the user or service that created the operation. ### Method `CreatedBy` ### Parameters: None ### Returns: - `string` — Creator ID ``` -------------------------------- ### Get Operation Creator ID Source: https://github.com/nebius/gosdk/blob/main/_autodocs/api-reference/operations.md Returns the identifier of the user or service that initiated the operation. ```go func (o Operation) CreatedBy() string { // ... implementation details ... } ``` -------------------------------- ### Create SDK with ServiceAccountCredentialsFileParser Source: https://github.com/nebius/gosdk/blob/main/_autodocs/api-reference/auth.md Use ServiceAccountCredentialsFileParser to initialize the SDK with credentials from a JSON file. The 'fs' parameter can be nil to use the real file system. ```go reader := auth.NewServiceAccountCredentialsFileParser( nil, "~/.config/nebius/service-account.json", ) ctx := context.Background() sdk, err := gosdk.New( ctx, gosdk.WithCredentials(gosdk.ServiceAccountReader(reader)), ) ``` -------------------------------- ### Configure SDK for Explicit Initialization Source: https://github.com/nebius/gosdk/blob/main/_autodocs/configuration.md Defers I/O operations from `gosdk.New()` to a manual `SDK.Init()` call. This separates SDK instantiation from network operations, allowing for deferred initialization. ```go sdk, err := gosdk.New( ctx, gosdk.WithExplicitInit(true), ) if err != nil { return err } // Perform I/O later if err := sdk.Init(ctx); err != nil { return err } ``` -------------------------------- ### Get Operation Finish Timestamp Source: https://github.com/nebius/gosdk/blob/main/_autodocs/api-reference/operations.md Returns the timestamp when the operation completed, or nil if it is still in progress. ```APIDOC ## Get Operation Finish Timestamp ### Description Returns the timestamp when the operation completed, or nil if still in progress. ### Method `FinishedAt` ### Parameters: None ### Returns: - `*time.Time` — Completion timestamp or nil if not yet done ### Example: ```go if finishedAt := operation.FinishedAt(); finishedAt != nil { duration := finishedAt.Sub(operation.CreatedAt()) log.Printf("Operation took %v", duration) } ``` ``` -------------------------------- ### Initialize SDK with Service Account Source: https://github.com/nebius/gosdk/blob/main/_autodocs/README.md Initialize the Nebius SDK using service account credentials from a JSON file. Ensure the service account file is correctly configured and accessible. ```go import "github.com/nebius/gosdk" import "github.com/nebius/gosdk/auth" sdk, err := gosdk.New( ctx, gosdk.WithCredentials( gosdk.ServiceAccountReader( auth.NewServiceAccountCredentialsFileParser(nil, "~/.config/nebius/sa.json"), ), ), gosdk.WithParentID("project-id"), ) defer sdk.Close() ``` -------------------------------- ### Get Parent ID Source: https://github.com/nebius/gosdk/blob/main/_autodocs/api-reference/sdk.md Retrieves the configured parent ID (project ID) for the SDK instance. ```APIDOC ## SDK ParentID ### Description Returns the parent ID (project ID) configured in the SDK, if any. ### Signature `func (s *SDK) ParentID() string` ### Parameters None ### Returns - `string` - Parent ID set via `WithParentID()` or from the config reader; empty if not set ### Example ```go parentID := sdk.ParentID() if parentID == "" { log.Println("No default parent ID configured") } ``` ``` -------------------------------- ### SDK Initialization with Custom Token Provider Source: https://github.com/nebius/gosdk/blob/main/_autodocs/api-reference/auth.md Initializes the SDK using a custom token provider implementation. Requires a struct that satisfies the CustomTokener interface. ```go customTokener := &myTokenProvider{} sdk, err := gosdk.New( ctx, gosdk.WithCredentials(gosdk.CustomTokener(customTokener)), ) ``` -------------------------------- ### Get Resource ID Source: https://github.com/nebius/gosdk/blob/main/_autodocs/api-reference/operations.md Returns the ID of the resource affected by the operation (created, updated, deleted, etc.). ```APIDOC ## Get Resource ID ### Description Returns the ID of the resource created, updated, deleted, or otherwise affected by the operation. ### Method `ResourceID` ### Parameters: None ### Returns: - `string` — Resource ID; may be empty if not applicable ### Example: ```go operation, err := operation.Wait(ctx) if err != nil { return err } instanceID := operation.ResourceID() log.Printf("Created instance: %s", instanceID) ``` ``` -------------------------------- ### Get Operation Progress Tracker Source: https://github.com/nebius/gosdk/blob/main/_autodocs/api-reference/operations.md Returns an interface for tracking operation progress if the operation supports progress reporting. ```go func (o Operation) ProgressTracker() OperationProgressTracker { // ... implementation details ... } ``` -------------------------------- ### Enable Logging with slog Handler Source: https://github.com/nebius/gosdk/blob/main/SCENARIOS.md Initialize the SDK using a pre-configured slog handler. This is useful when you have specific handler configurations. ```go handler := slog.NewJSONHandler(os.Stdout, nil) sdk, err := gosdk.New(ctx, gosdk.WithLoggerHandler(handler)) ``` -------------------------------- ### SDK Initialization Source: https://github.com/nebius/gosdk/blob/main/_autodocs/api-reference/sdk.md Initializes a new Nebius Go SDK instance. This is the main entry point for interacting with Nebius services. ```APIDOC ## New SDK Initialization ### Description Creates and initializes a new SDK instance with the provided options. This function manages gRPC connections, authentication, and provides access to all available services. ### Signature `func New(ctx context.Context, opts ...Option) (*SDK, error)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **ctx** (`context.Context`) - Required - Short-lived context used only for initialization. The context does not need to outlive the function call. - **opts** (`...Option`) - Optional - Variadic options to configure the SDK instance. See [Configuration](../configuration.md) for all options. ### Returns - `*SDK` - Initialized SDK instance ready to use - `error` - Error if initialization fails (e.g., invalid credentials, missing configuration) ### Notes - By default, `New` automatically calls `Init()` to perform I/O operations. Use `WithExplicitInit(true)` to defer initialization. - Authorization is required for most functionality. Use `WithCredentials()` to provide credentials. - Call `Close()` when finished to clean up resources and close connections. - The provided context is only used during setup; long-lived operations use the context returned by `SDK.Context()`. ### Example ```go import "github.com/nebius/gosdk" ctx := context.Background() sdk, err := gosdk.New( ctx, gosdk.WithCredentials(gosdk.IAMToken(token)), gosdk.WithTimeout(2 * time.Minute), ) if err != nil { return fmt.Errorf("create sdk: %w", err) } defer sdk.Close() ``` ``` -------------------------------- ### Get Original Operation Request Source: https://github.com/nebius/gosdk/blob/main/_autodocs/api-reference/operations.md Retrieves the initial request message that triggered the operation. This may be nil if not available. ```go func (o Operation) Request() proto.Message { // ... implementation details ... } ``` -------------------------------- ### Go SDK Create Resource Operation Source: https://github.com/nebius/gosdk/blob/main/_autodocs/api-reference/services.md Demonstrates how to create a new resource, wait for the operation to complete, and retrieve the resource ID. ```go service := sdk.Services().Compute().V1().Instance() operation, err := service.Create(ctx, &compute.CreateInstanceRequest{ Metadata: &common.ResourceMetadata{ ParentId: parentID, Name: "instance-name", }, Spec: &compute.InstanceSpec{ // resource configuration }, }) if err != nil { return err } // Wait for creation operation, err = operation.Wait(ctx) if err != nil { return err } resourceID := operation.ResourceID() ``` -------------------------------- ### Explicitly Initialize SDK Source: https://github.com/nebius/gosdk/blob/main/_autodocs/api-reference/sdk.md Initialize the SDK explicitly after creation, typically when `WithExplicitInit(true)` is used during construction. This allows deferring I/O operations until a later point. ```go sdk, err := gosdk.New( ctx, gosdk.WithExplicitInit(true), gosdk.WithCredentials(gosdk.IAMToken(token)), ) if err != nil { return err } // Perform I/O operations later if err := sdk.Init(ctx); err != nil { return err } ``` -------------------------------- ### SDK Initialization Source: https://github.com/nebius/gosdk/blob/main/_autodocs/REFERENCE.md Functions for initializing and managing the Nebius Go SDK instance. ```APIDOC ## SDK Initialization ### `gosdk.New()` #### Description Creates a new instance of the Nebius Go SDK. ### `sdk.Init()` #### Description Explicitly initializes the SDK, setting up necessary resources. ### `sdk.Close()` #### Description Cleans up SDK resources, releasing any held connections or memory. ### `sdk.Context()` #### Description Retrieves the long-lived context associated with the SDK instance. ### `sdk.Services()` #### Description Provides access to the various service interfaces available through the SDK. ``` -------------------------------- ### Handle Context Canceled in Go Source: https://github.com/nebius/gosdk/blob/main/_autodocs/errors.md Detect when an operation is canceled via a context. This example uses `context.WithCancel` and `errors.Is` to check for `context.Canceled`. ```go ctx, cancel := context.WithCancel(context.Background()) go func() { time.Sleep(1 * time.Second) cancel() }() operation, err := operation.Wait(ctx) if errors.Is(err, context.Canceled) { return fmt.Errorf("operation wait canceled: %w", err) } ``` -------------------------------- ### SDK Initialization (Explicit) Source: https://github.com/nebius/gosdk/blob/main/_autodocs/api-reference/sdk.md Manually initializes the SDK instance, performing required I/O operations. ```APIDOC ## SDK Init ### Description Finalizes SDK creation by performing all required I/O operations. Automatically called by `New()` unless `WithExplicitInit(true)` is set. ### Signature `func (s *SDK) Init(ctx context.Context) error` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **ctx** (`context.Context`) - Required - Context for initialization operations ### Returns - `error` - Initialization error if any I/O operation fails ### Behavior - Safe to call multiple times; subsequent calls are no-ops after the first successful call - Executes all registered initialization functions in order - Must be called if `WithExplicitInit(true)` was used during SDK creation ### Example ```go sdk, err := gosdk.New( ctx, gosdk.WithExplicitInit(true), gosdk.WithCredentials(gosdk.IAMToken(token)), ) if err != nil { return err } // Perform I/O operations later if err := sdk.Init(ctx); err != nil { return err } ``` ``` -------------------------------- ### Get Operation Progress Data Source: https://github.com/nebius/gosdk/blob/main/_autodocs/api-reference/operations.md Retrieves additional progress information while the operation is running. Returns nil if no progress data is available. ```go func (o Operation) ProgressData() proto.Message { // ... implementation details ... } ``` -------------------------------- ### Configure SDK with Auth Options Source: https://github.com/nebius/gosdk/blob/main/_autodocs/configuration.md Passes options to auth-layer implementations. Supports cached tokeners, federation, and workload identity. ```go sdk, err := gosdk.New( ctx, gosdk.WithAuthOptions( auth.WithLogger(logger), ), ) ``` -------------------------------- ### Get Original Request Headers Source: https://github.com/nebius/gosdk/blob/main/_autodocs/api-reference/operations.md Returns a copy of the HTTP headers from the original request that initiated the operation. These headers can be safely modified. ```go func (o Operation) RequestHeaders() http.Header { // ... implementation details ... } ``` -------------------------------- ### Get Operation Source: https://github.com/nebius/gosdk/blob/main/_autodocs/api-reference/services.md Retrieves a specific resource by its unique identifier. This is a direct retrieval method that returns the resource object upon success. ```APIDOC ## Get Operation ### Description Retrieves a resource by its unique ID. ### Method GET (implied by Get operation) ### Endpoint `/path/to/resource/{id}` (specific to the service, e.g., `/compute/v1/instances/{id}`) ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the resource to retrieve. #### Request Body - **req** (*GetRequest) - Required - The request object containing the ID of the resource. ### Request Example ```go instance, err := service.Get(ctx, &compute.GetInstanceRequest{ Id: resourceID, }) ``` ### Response #### Success Response (200) - **Resource** (*Resource) - The retrieved resource object. ### Response Example ```go // instance object details ``` ``` -------------------------------- ### Get Resource ID Affected by Operation Source: https://github.com/nebius/gosdk/blob/main/_autodocs/api-reference/operations.md Returns the ID of the resource that was created, updated, or deleted by the operation. This may be an empty string if not applicable. ```go operation, err := operation.Wait(ctx) if err != nil { return err } instanceID := operation.ResourceID() log.Printf("Created instance: %s", instanceID) ``` -------------------------------- ### Enable Logging with slog Logger Source: https://github.com/nebius/gosdk/blob/main/SCENARIOS.md Initialize the SDK with a custom slog logger instance. Ensure the logger is configured before passing it to gosdk.New. ```go logger := slog.New(slog.NewJSONHandler(os.Stdout, nil)) sdk, err := gosdk.New(ctx, gosdk.WithLogger(logger)) ``` -------------------------------- ### Get Compute Instance by ID Source: https://github.com/nebius/gosdk/blob/main/README.md Fetches a compute instance using its ID after an operation has completed. This operation retrieves the current state of the resource. ```go instance, err := instanceService.Get(ctx, &compute.GetInstanceRequest{ Id: instanceID, }) if err != nil { return fmt.Errorf("get instance: %w", err) } ``` -------------------------------- ### Create Service Account Credentials File Parser Source: https://github.com/nebius/gosdk/blob/main/_autodocs/api-reference/credentials.md Creates a reader to parse service account credentials from a JSON file. Use nil for the file system to use the real file system. The credentials path supports `~/` expansion. ```go reader := auth.NewServiceAccountCredentialsFileParser( nil, "~/.config/nebius/service-account.json", ) sdk, err := gosdk.New( ctx, gosdk.WithCredentials(gosdk.ServiceAccountReader(reader)), ) ``` -------------------------------- ### Using CLI Config Reader in Go SDK Source: https://github.com/nebius/gosdk/blob/main/_autodocs/api-reference/utilities.md Configure the SDK to use the CLI configuration reader, which loads settings from `~/.config/nebius/config.yaml`. This is done by passing `reader.NewCliConfig()` to `gosdk.New`. ```go import "github.com/nebius/gosdk/config/reader" sdk, err := gosdk.New( ctx, gosdk.WithConfigReader(reader.NewCliConfig(opts...)), ) ``` -------------------------------- ### Retrieve Configured Tenant ID Source: https://github.com/nebius/gosdk/blob/main/_autodocs/api-reference/sdk.md Get the tenant ID configured for the SDK instance. This is used for operations requiring a tenant as the parent ID. ```go tenantID := sdk.TenantID() ``` -------------------------------- ### Create Mock Operation Stub Source: https://github.com/nebius/gosdk/blob/main/_autodocs/api-reference/utilities.md Shows how to create a mock operation stub using the operations mock package for use in tests. ```go import "github.com/nebius/gosdk/mocks/operations" stub := operations.NewStub() // Use stub in tests ``` -------------------------------- ### Configure SDK with Metrics Source: https://github.com/nebius/gosdk/blob/main/_autodocs/configuration.md Enables metrics collection for config reading and authentication. Propagates metrics to config reader and auth components. ```go sdk, err := gosdk.New( ctx, gosdk.WithMetrics(metricsRecorder), ) ``` -------------------------------- ### Handle Context Deadline Exceeded in Go Source: https://github.com/nebius/gosdk/blob/main/_autodocs/errors.md Check if a request timed out due to a context deadline. This example uses `context.WithTimeout` and `errors.Is` to detect `context.DeadlineExceeded`. ```go ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) deferr cancel() instance, err := service.Get(ctx, request) if errors.Is(err, context.DeadlineExceeded) { return fmt.Errorf("request timeout: %w", err) } ``` -------------------------------- ### Handle Service Errors in Go Source: https://github.com/nebius/gosdk/blob/main/_autodocs/REFERENCE.md Demonstrates how to check for and handle specific service errors, such as 'NotFound', when interacting with the SDK. It's crucial to inspect the error details for granular control. ```go instance, err := service.Get(ctx, request) if err != nil { var svcErr *serviceerror.Error if errors.As(err, &svcErr) { for _, detail := range svcErr.Details { if nf, ok := detail.(*serviceerror.NotFound); ok { return fmt.Errorf("resource not found: %v", nf) } } } return err } ``` -------------------------------- ### Get Raw Operation Protobuf Source: https://github.com/nebius/gosdk/blob/main/_autodocs/api-reference/operations.md Access the underlying protobuf representation of an operation. This is useful for inspecting the full operation details as defined in the proto schema. ```go func (o Operation) Raw() *common.Operation ``` -------------------------------- ### Create Resource and Wait for Operation Source: https://github.com/nebius/gosdk/blob/main/_autodocs/README.md Create a new resource and then wait for the asynchronous operation to complete. This pattern is common for actions that take time to provision or modify. ```go operation, err := service.Create(ctx, &CreateRequest{...}) if err != nil { return err } operation, err = operation.Wait(ctx) if err != nil { return err } resourceID := operation.ResourceID() ``` -------------------------------- ### Get Bearer Token Source: https://github.com/nebius/gosdk/blob/main/_autodocs/api-reference/sdk.md Fetches the current bearer token for authentication. Use this when you need to make authenticated API calls or inspect token expiration. ```go token, err := sdk.BearerToken(ctx) if err != nil { return err } log.Printf("Token expires at: %v", token.ExpiresAt) ``` -------------------------------- ### Common Operation Usage Source: https://github.com/nebius/gosdk/blob/main/_autodocs/api-reference/utilities.md Illustrates the typical workflow for creating an operation, waiting for its completion, and retrieving the resource ID. ```go operation, err := service.Create(ctx, request) if err != nil { return err } // Wait for completion operation, err = operation.Wait(ctx) if err != nil { return err } resourceID := operation.ResourceID() ``` -------------------------------- ### List Compute Instances with Pagination Source: https://github.com/nebius/gosdk/blob/main/README.md Retrieves a list of compute instances within a specified project. Handles pagination for large result sets by checking and using `NextPageToken`. ```go list, err := instanceService.List(ctx, &compute.ListInstancesRequest{ ParentId: "my-project-id", }) if err != nil { return fmt.Errorf("list instances: %w", err) } for _, instance := range list.GetItems() { // process instance } if list.GetNextPageToken() != "" { list, err = instanceService.List(ctx, &compute.ListInstancesRequest{ ParentId: "my-project-id", PageToken: list.GetNextPageToken(), }) if err != nil { return fmt.Errorf("list instances: %w", err) } // repeat processing } ``` -------------------------------- ### Configure SDK with Auth Metrics Source: https://github.com/nebius/gosdk/blob/main/_autodocs/configuration.md Enables metrics collection for authentication only. Use when metrics don't implement config-reader callbacks. ```go sdk, err := gosdk.New( ctx, gosdk.WithAuthMetrics(authMetricsRecorder), ) ``` -------------------------------- ### Get Logger Instance Source: https://github.com/nebius/gosdk/blob/main/_autodocs/api-reference/sdk.md Retrieves the logger instance configured for the SDK. This is useful for logging SDK-related events or integrating SDK logs with your application's logging. ```go func (s *SDK) GetLogger() *slog.Logger { return s.logger } ``` -------------------------------- ### Retrieve Configured Parent ID Source: https://github.com/nebius/gosdk/blob/main/_autodocs/api-reference/sdk.md Get the parent ID (project ID) that was configured for the SDK instance. Returns an empty string if no default parent ID was set. ```go parentID := sdk.ParentID() if parentID == "" { log.Println("No default parent ID configured") } ``` -------------------------------- ### View Makefile Commands Source: https://github.com/nebius/gosdk/blob/main/CONTRIBUTING.md Display a list of all available commands defined in the project's Makefile. This helps in understanding and utilizing project automation scripts. ```bash make help ```