Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions docs/data-sources/browser_pool.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
---
# generated by https://github.com/hashicorp/terraform-plugin-docs
page_title: "kernel_browser_pool Data Source - Kernel"
subcategory: ""
description: |-
Lookup durable Kernel browser pool configuration.
---

# kernel_browser_pool (Data Source)

Lookup durable Kernel browser pool configuration.



<!-- schema generated by tfplugindocs -->
## Schema

### Optional

- `id` (String) Browser pool ID.
- `name` (String) Browser pool name for exact lookup.
- `project_id` (String) Project to look the browser pool up in. Defaults to the provider `project_id`; when neither is set, the API key's project binding determines the project.

### Read-Only

- `size` (Number) Number of browsers maintained in the pool.
216 changes: 216 additions & 0 deletions internal/datasources/browserpool/datasource.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,216 @@
package browserpool

import (
"context"
"encoding/json"
"strconv"

"github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator"
"github.com/hashicorp/terraform-plugin-framework/datasource"
dschema "github.com/hashicorp/terraform-plugin-framework/datasource/schema"
"github.com/hashicorp/terraform-plugin-framework/diag"
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
"github.com/hashicorp/terraform-plugin-framework/types"
kernel "github.com/kernel/kernel-go-sdk"
"github.com/kernel/terraform-provider-kernel/internal/datasources"
"github.com/kernel/terraform-provider-kernel/internal/projectscope"
)

var (
_ datasource.DataSource = (*browserPoolDataSource)(nil)
_ datasource.DataSourceWithConfigure = (*browserPoolDataSource)(nil)
)

type browserPoolClient interface {
DefaultProjectID() string
GetBrowserPool(context.Context, string, string) (*kernel.BrowserPool, error)
}

type browserPoolDataSource struct {
client browserPoolClient
}

type browserPoolModel struct {
ID types.String `tfsdk:"id"`
Name types.String `tfsdk:"name"`
ProjectID types.String `tfsdk:"project_id"`
Size types.Int64 `tfsdk:"size"`
}

func NewDataSource() datasource.DataSource {
return &browserPoolDataSource{}
}

func newDataSourceWithClient(client browserPoolClient) *browserPoolDataSource {
return &browserPoolDataSource{client: client}
}

func (d *browserPoolDataSource) Metadata(_ context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_browser_pool"
}

func (d *browserPoolDataSource) Schema(_ context.Context, _ datasource.SchemaRequest, resp *datasource.SchemaResponse) {
resp.Schema = dschema.Schema{
MarkdownDescription: "Lookup durable Kernel browser pool configuration.",
Attributes: map[string]dschema.Attribute{
"id": dschema.StringAttribute{
Optional: true,
Computed: true,
MarkdownDescription: "Browser pool ID.",
},
"name": dschema.StringAttribute{
Optional: true,
Computed: true,
MarkdownDescription: "Browser pool name for exact lookup.",
},
"project_id": dschema.StringAttribute{
Optional: true,
MarkdownDescription: "Project to look the browser pool up in. Defaults to the provider `project_id`; when neither is set, the API key's project binding determines the project.",
Validators: []validator.String{
stringvalidator.LengthAtLeast(1),
},
},
"size": dschema.Int64Attribute{
Computed: true,
MarkdownDescription: "Number of browsers maintained in the pool.",
},
},
}
}

func (d *browserPoolDataSource) Configure(_ context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) {
if req.ProviderData == nil {
return
}

client, ok := req.ProviderData.(browserPoolClient)
if !ok {
resp.Diagnostics.AddError(
"Unexpected Kernel Client Type",
"Expected provider data to implement the browser pool data source durable client contract.",
)
return
}
d.client = client
}

func (d *browserPoolDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) {
var config browserPoolModel
resp.Diagnostics.Append(req.Config.Get(ctx, &config)...)
if resp.Diagnostics.HasError() {
return
}

state, diags := d.read(ctx, config)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
resp.Diagnostics.Append(resp.State.Set(ctx, state)...)
}

func (d *browserPoolDataSource) read(ctx context.Context, config browserPoolModel) (browserPoolModel, diag.Diagnostics) {
var diags diag.Diagnostics
if d.client == nil {
diags.AddError("Missing Kernel Client", "The browser pool data source was not configured with a Kernel client.")
return browserPoolModel{}, diags
}

selector, selectorDiags := datasources.ResolveIDNameSelector("Browser Pool", "kernel_browser_pool", config.ID, config.Name)
diags.Append(selectorDiags...)
if diags.HasError() {
return browserPoolModel{}, diags
}

projectID := projectscope.ResolveDataSource(&diags, config.ProjectID, d.client.DefaultProjectID())
if diags.HasError() {
return browserPoolModel{}, diags
}

var idOrName string
switch {
case selector.HasID:
idOrName = config.ID.ValueString()
case selector.HasName:
idOrName = config.Name.ValueString()
default:
diags.AddError("Missing Browser Pool Selector", "Configure id or name for kernel_browser_pool.")
return browserPoolModel{}, diags
}

pool, err := d.client.GetBrowserPool(ctx, projectID, idOrName)
if err != nil {
projectscope.AddError(&diags, "Read Kernel Browser Pool", projectID, err)
return browserPoolModel{}, diags
}
if pool == nil {
diags.AddError("Read Kernel Browser Pool", "Kernel returned an empty browser pool response.")
return browserPoolModel{}, diags
}

state, flattenDiags := flattenBrowserPool(*pool)
diags.Append(flattenDiags...)
if diags.HasError() {
return browserPoolModel{}, diags
}
if selector.HasID && state.ID.ValueString() != config.ID.ValueString() {
diags.AddError(
"Browser Pool ID Mismatch",
"Kernel returned browser pool "+strconv.Quote(state.ID.ValueString())+" for id selector "+strconv.Quote(config.ID.ValueString())+".",
)
return browserPoolModel{}, diags
}
if selector.HasName && (state.Name.IsNull() || state.Name.ValueString() != config.Name.ValueString()) {
diags.AddError(
"Browser Pool Name Mismatch",
"Kernel returned a browser pool whose name does not match exact selector "+strconv.Quote(config.Name.ValueString())+".",
)
return browserPoolModel{}, diags
}

state.ProjectID = config.ProjectID
return state, diags
}

func flattenBrowserPool(pool kernel.BrowserPool) (browserPoolModel, diag.Diagnostics) {
var diags diag.Diagnostics
if !datasources.ValidResponseString(pool.JSON.ID.Raw(), pool.JSON.ID.Valid(), pool.ID) {
datasources.AddInvalidResponseField(&diags, "Browser Pool", "id")
}
if !validResponseInt64(pool.BrowserPoolConfig.JSON.Size.Raw(), pool.BrowserPoolConfig.JSON.Size.Valid(), pool.BrowserPoolConfig.Size) || pool.BrowserPoolConfig.Size < 1 {
datasources.AddInvalidResponseField(&diags, "Browser Pool", "browser_pool_config.size")
}

name := types.StringNull()
switch {
case datasources.FieldPresent(pool.JSON.Name.Raw()):
if !datasources.ValidResponseString(pool.JSON.Name.Raw(), pool.JSON.Name.Valid(), pool.Name) {
datasources.AddInvalidResponseField(&diags, "Browser Pool", "name")
} else {
name = types.StringValue(pool.Name)
}
case datasources.FieldPresent(pool.BrowserPoolConfig.JSON.Name.Raw()):
if !datasources.ValidResponseString(pool.BrowserPoolConfig.JSON.Name.Raw(), pool.BrowserPoolConfig.JSON.Name.Valid(), pool.BrowserPoolConfig.Name) {
datasources.AddInvalidResponseField(&diags, "Browser Pool", "browser_pool_config.name")
} else {
name = types.StringValue(pool.BrowserPoolConfig.Name)
}
}
if diags.HasError() {
return browserPoolModel{}, diags
}

return browserPoolModel{
ID: types.StringValue(pool.ID),
Name: name,
Size: types.Int64Value(pool.BrowserPoolConfig.Size),
}, diags
}

func validResponseInt64(raw string, valid bool, value int64) bool {
if !datasources.FieldPresent(raw) || !valid {
return false
}
var decoded int64
return json.Unmarshal([]byte(raw), &decoded) == nil && decoded == value
}
Comment thread
cursor[bot] marked this conversation as resolved.
Loading