repo_name
stringlengths
1
52
repo_creator
stringclasses
6 values
programming_language
stringclasses
4 values
code
stringlengths
0
9.68M
num_lines
int64
1
234k
jsii-rosetta
aws
Go
x := map[string]*string{ "key": jsii.String("value"), }
4
jsii-rosetta
aws
Go
callThisFunction(foo, ...)
2
jsii-rosetta
aws
Go
fmt.Println(enumType_ENUM_VALUE_A)
2
jsii-rosetta
aws
Go
fmt.Println(enumType_ENUM_VALUE_A())
2
jsii-rosetta
aws
Go
map := map[string]interface{}{ "Access-Control-Allow-Origin": jsii.String("\"*\""), }
4
jsii-rosetta
aws
Go
x := someObject.someAttribute
2
jsii-rosetta
aws
Go
object.propertyA object.propertyB
3
jsii-rosetta
aws
Go
x := "world" y := "well" fmt.Println(fmt.Sprintf("Hello, %v, it works %v!", x, y)) // And now a multi-line expression fmt.Println(fmt.Sprintf("\nHello, %v.\n\nIt works %v!\n", x, y))
7
jsii-rosetta
aws
Go
literal := ` This is a multiline string literal. "It's cool!". YEAH BABY!! Litteral \\n right here (not a newline!) `
10
jsii-rosetta
aws
Go
type test struct { key *string } x := &test{ key: jsii.String("value"), }
8
jsii-rosetta
aws
Go
fmt.Println(-3) fmt.Println(!false) fmt.Println(a == b)
4
jsii-rosetta
aws
Go
if true { fmt.Println("everything is well") } onlyToEndOfBlock()
6
jsii-rosetta
aws
Go
foo(jsii.Number(3), ...)
2
jsii-rosetta
aws
Go
prepare() fmt.Println(this, "it seems to work")
4
jsii-rosetta
aws
Go
foo(jsii.Number(3), jsii.Number(8))
2
jsii-rosetta
aws
Go
before() // ... after()
4
jsii-rosetta
aws
Go
foo(jsii.Number(3))
2
jsii-rosetta
aws
Go
import lambda "github.com/aws-samples/dummy/scopeawslambda" lambda.NewClassFromLambda(map[string]*string{ "key": jsii.String("lambda.amazonaws.com"), })
5
jsii-rosetta
aws
Go
import mod "github.com/aws-samples/dummy/scopesomemodule" mod.NewClassFromModule()
3
jsii-rosetta
aws
Go
import mod "github.com/aws-samples/dummy/scopesomemodule" mod.NewClassFromModule()
3
jsii-rosetta
aws
Go
import cdk "github.com/aws-samples/dummy/awscdklib" import "github.com/aws-samples/dummy/constructs"
3
jsii-rosetta
aws
Go
import "github.com/aws-samples/dummy/scopesomemodule" scopesomemodule.NewTwo() scopesomemodule.Four()
4
jsii-rosetta
aws
Go
import "github.com/aws/jsii/jsii-calc/go/jsiicalc/submodule" import "github.com/aws/jsii/jsii-calc/go/jsiicalc/submodule/child" import "github.com/aws/jsii/jsii-calc/go/jsiicalc" import "github.com/aws/jsii/jsii-calc/go/jsiicalc/foo" import "github.com/aws-samples/dummy/gen/providers/aws/kms" // Access without existing type information awsKmsKeyExamplekms := kms.NewKmsKey(this, jsii.String("examplekms"), map[string]interface{}{ "deletionWindowInDays": jsii.Number(7), "description": jsii.String("KMS key 1"), }) // Accesses two distinct points of the submodule hierarchy myClass := submodule.NewMyClass(&SomeStruct{ Prop: child.SomeEnum_SOME, }) // Access via a renamed import foo.Consumer_Consume(&ConsumerProps{ Homonymous: &Homonymous{ StringProperty: jsii.String("yes"), }, })
24
jsii-rosetta
aws
Go
type iThing interface { doAThing() }
4
jsii-rosetta
aws
Go
type iThing interface { thingArn() *string }
4
jsii-rosetta
aws
Go
callFunction(jsii.Boolean(true), jsii.Boolean(false))
2
jsii-rosetta
aws
Go
if x == 3 { fmt.Println("hello") }
4
jsii-rosetta
aws
Go
var variable Type
2
jsii-rosetta
aws
Go
if x == 3 {}
2
jsii-rosetta
aws
Go
for _, x := range xs { fmt.Println(x) }
4
jsii-rosetta
aws
Go
if x == 3 { fmt.Println("bye") }
4
jsii-rosetta
aws
Go
if x == 3 { fmt.Println("bye") } else { fmt.Println("toodels") }
6
jsii-rosetta
aws
Go
expected := map[string]interface{}{ "Foo": jsii.String("Bar"), "Baz": jsii.Number(5), "Qux": []*string{ jsii.String("Waldo"), jsii.String("Fred"), }, }
9
jsii-rosetta
aws
Go
if x == 3 { x += 1 fmt.Println("bye") } else { fmt.Println("toodels") }
7
jsii-rosetta
aws
Go
func doThing() *f64 { x := 1 // x seems to be equal to 1 return jsii.Number(x + 1) } func doThing2(x *f64) *bool { if *x == 1 { return jsii.Boolean(true) } return jsii.Boolean(false) } func doThing3() *f64 { x := 1 return jsii.Number(x + 1) } func doThing4() { x := 1 x = 85 }
22
jsii-rosetta
aws
Go
func test(..._args interface{}) { } test(map[string]interface{}{ "Key": jsii.String("Value"), "also": jsii.Number(1337), }) test(map[string]*string{ "Key": jsii.String("Value"), }, map[string]*f64{ "also": jsii.Number(1337), })
14
jsii-rosetta
aws
Go
statementOne() statementTwo()
4
jsii-rosetta
aws
Go
if condition { statementOne() statementTwo() }
6
jsii-rosetta
aws
Go
functionThatTakesAnAny(map[string]*f64{ "argument": jsii.Number(5), })
4
jsii-rosetta
aws
Go
takes(&myProps{ Struct: &someStruct{ Enabled: jsii.Boolean(false), Option: jsii.String("option"), }, })
9
jsii-rosetta
aws
Go
NewVpc(this, jsii.String("Something"), &vpcProps{ Argument: jsii.Number(5), })
4
jsii-rosetta
aws
Go
NewIntegration(this, jsii.String("Something"), &integrationOptions{ Argument: jsii.Number(5), })
4
jsii-rosetta
aws
Go
vpc := NewVpc(this, jsii.String("Something"), &vpcProps{ Argument: jsii.Number(5), })
4
jsii-rosetta
aws
Go
vpc := NewVpc(this, jsii.String("Something"), map[string]*f64{ "argument": jsii.Number(5), })
4
jsii-runtime-go
aws
Go
package jsii import ( "fmt" "reflect" "github.com/aws/jsii-runtime-go/internal/kernel" ) // UnsafeCast converts the given interface value to the desired target interface // pointer. Panics if the from value is not a jsii proxy object, or if the to // value is not a pointer to an interface type. func UnsafeCast(from interface{}, into interface{}) { rinto := reflect.ValueOf(into) if rinto.Kind() != reflect.Ptr { panic(fmt.Errorf("second argument to UnsafeCast must be a pointer to an interface; received %v", rinto.Type())) } rinto = rinto.Elem() if rinto.Kind() != reflect.Interface { panic(fmt.Errorf("second argument to UnsafeCast must be a pointer to an interface; received pointer to %v", rinto.Type())) } rfrom := reflect.ValueOf(from) // If rfrom is essentially nil, set into to nil and return. if !rfrom.IsValid() || rfrom.IsZero() { null := reflect.Zero(rinto.Type()) rinto.Set(null) return } // Interfaces may present as a pointer to an implementing struct, and that's fine... if rfrom.Kind() != reflect.Interface && rfrom.Kind() != reflect.Ptr { panic(fmt.Errorf("first argument to UnsafeCast must be an interface value; received %v", rfrom.Type())) } // If rfrom can be directly converted to rinto, just do it. if rfrom.Type().AssignableTo(rinto.Type()) { rfrom = rfrom.Convert(rinto.Type()) rinto.Set(rfrom) return } client := kernel.GetClient() if objID, found := client.FindObjectRef(rfrom); found { // Ensures the value is initialized properly. Panics if the target value is not a jsii interface type. client.Types().InitJsiiProxy(rinto, rinto.Type()) // If the target type is a behavioral interface, add it to the ObjectRef.Interfaces list. if fqn, found := client.Types().InterfaceFQN(rinto.Type()); found { objID.Interfaces = append(objID.Interfaces, fqn) } // Make the new value an alias to the old value. client.RegisterInstance(rinto, objID) return } panic(fmt.Errorf("first argument to UnsafeCast must be a jsii proxy value; received %v", rfrom)) }
60
jsii-runtime-go
aws
Go
package jsii import ( "reflect" "testing" "github.com/aws/jsii-runtime-go/internal/api" "github.com/aws/jsii-runtime-go/internal/kernel" ) type MockInterfaceABase interface { MockMethodABase(_ float64) } type mockABase struct { _ int // padding } func (m *mockABase) MockMethodABase(_ float64) {} type MockInterfaceA interface { MockInterfaceABase MockMethodA(_ string) } func NewMockInterfaceA() MockInterfaceA { return &mockA{mockABase{}} } type mockA struct { mockABase } func (m *mockA) MockMethodA(_ string) {} type MockInterfaceB interface { MockMethodB(_ int) } func NewMockInterfaceB() MockInterfaceB { return &mockB{} } type mockB struct { _ int // Padding } func (m *mockB) MockMethodB(_ int) {} func TestNilSource(t *testing.T) { // Make "into" not nil to ensure the cast function overwrites it. into := NewMockInterfaceB() UnsafeCast(nil, &into) if into != nil { t.Fail() } } func TestSourceAndTargetAreTheSame(t *testing.T) { into := NewMockInterfaceB() original := into UnsafeCast(into, &into) if into != original { t.Fail() } } func TestTargetIsSubclassOfSource(t *testing.T) { from := NewMockInterfaceA() var into MockInterfaceABase UnsafeCast(from, &into) if into != from { t.Fail() } } func TestRegistersAlias(t *testing.T) { client := kernel.GetClient() objid := api.ObjectRef{InstanceID: "Object@1337#42"} from := NewMockInterfaceA() client.RegisterInstance(reflect.ValueOf(from), objid) var into MockInterfaceB client.Types().RegisterInterface(api.FQN("mock.InterfaceB"), reflect.TypeOf(&into).Elem(), []api.Override{}, func() interface{} { return NewMockInterfaceB() }) UnsafeCast(from, &into) if into == nil { t.Fail() } if refid, found := client.FindObjectRef(reflect.ValueOf(into)); !found { t.Fail() } else if refid.InstanceID != objid.InstanceID { t.Fail() } }
102
jsii-runtime-go
aws
Go
package jsii import ( "reflect" "github.com/aws/jsii-runtime-go/internal/api" "github.com/aws/jsii-runtime-go/runtime" ) // Deprecated: FQN represents a fully-qualified type name in the jsii type system. type FQN api.FQN // Deprecated: Member is a runtime descriptor for a class or interface member type Member interface { asRuntimeMember() runtime.Member } // Deprecated: MemberMethod is a runtime descriptor for a class method (implementation of Member) type MemberMethod api.MethodOverride func (m MemberMethod) asRuntimeMember() runtime.Member { return runtime.MemberMethod(m) } // Deprecated: MemberProperty is a runtime descriptor for a class or interface property (implementation of Member) type MemberProperty api.PropertyOverride func (m MemberProperty) asRuntimeMember() runtime.Member { return runtime.MemberProperty(m) } // Deprecated: Load ensures a npm package is loaded in the jsii kernel. func Load(name string, version string, tarball []byte) { runtime.Load(name, version, tarball) } // Deprecated: RegisterClass associates a class fully qualified name to the specified class // interface, member list, and proxy maker function. Panics if class is not a go // interface, or if the provided fqn was already used to register a different type. func RegisterClass(fqn FQN, class reflect.Type, members []Member, maker func() interface{}) { rm := make([]runtime.Member, len(members)) for i, m := range members { rm[i] = m.asRuntimeMember() } runtime.RegisterClass(runtime.FQN(fqn), class, rm, maker) } // Deprecated: RegisterEnum associates an enum's fully qualified name to the specified enum // type, and members. Panics if enum is not a reflect.String type, any value in // the provided members map is of a type other than enum, or if the provided // fqn was already used to register a different type. func RegisterEnum(fqn FQN, enum reflect.Type, members map[string]interface{}) { runtime.RegisterEnum(runtime.FQN(fqn), enum, members) } // Deprecated: RegisterInterface associates an interface's fully qualified name to the // specified interface type, member list, and proxy maker function. Panics if iface is not // an interface, or if the provided fqn was already used to register a different type. func RegisterInterface(fqn FQN, iface reflect.Type, members []Member, maker func() interface{}) { rm := make([]runtime.Member, len(members)) for i, m := range members { rm[i] = m.asRuntimeMember() } runtime.RegisterInterface(runtime.FQN(fqn), iface, rm, maker) } // Deprecated: RegisterStruct associates a struct's fully qualified name to the specified // struct type. Panics if strct is not a struct, or if the provided fqn was // already used to register a different type. func RegisterStruct(fqn FQN, strct reflect.Type) { runtime.RegisterStruct(runtime.FQN(fqn), strct) } // Deprecated: InitJsiiProxy initializes a jsii proxy instance at the provided pointer. // Panics if the pointer cannot be initialized to a proxy instance (i.e: the // element of it is not a registered jsii interface or class type). func InitJsiiProxy(ptr interface{}) { runtime.InitJsiiProxy(ptr) } // Deprecated: Create will construct a new JSII object within the kernel runtime. This is // called by jsii object constructors. func Create(fqn FQN, args []interface{}, inst interface{}) { runtime.Create(runtime.FQN(fqn), args, inst) } // Deprecated: Invoke will call a method on a jsii class instance. The response will be // decoded into the expected return type for the method being called. func Invoke(obj interface{}, method string, args []interface{}, ret interface{}) { runtime.Invoke(obj, method, args, ret) } // Deprecated: InvokeVoid will call a void method on a jsii class instance. func InvokeVoid(obj interface{}, method string, args []interface{}) { runtime.InvokeVoid(obj, method, args) } // Deprecated: StaticInvoke will call a static method on a given jsii class. The response // will be decoded into the expected return type for the method being called. func StaticInvoke(fqn FQN, method string, args []interface{}, ret interface{}) { runtime.StaticInvoke(runtime.FQN(fqn), method, args, ret) } // Deprecated: StaticInvokeVoid will call a static void method on a given jsii class. func StaticInvokeVoid(fqn FQN, method string, args []interface{}) { runtime.StaticInvokeVoid(runtime.FQN(fqn), method, args) } // Deprecated: Get reads a property value on a given jsii class instance. The response // should be decoded into the expected type of the property being read. func Get(obj interface{}, property string, ret interface{}) { runtime.Get(obj, property, ret) } // Deprecated: StaticGet reads a static property value on a given jsii class. The response // should be decoded into the expected type of the property being read. func StaticGet(fqn FQN, property string, ret interface{}) { runtime.StaticGet(runtime.FQN(fqn), property, ret) } // Deprecated: Set writes a property on a given jsii class instance. The value should match // the type of the property being written, or the jsii kernel will crash. func Set(obj interface{}, property string, value interface{}) { runtime.Set(obj, property, value) } // Deprecated: StaticSet writes a static property on a given jsii class. The value should // match the type of the property being written, or the jsii kernel will crash. func StaticSet(fqn FQN, property string, value interface{}) { runtime.StaticSet(runtime.FQN(fqn), property, value) }
132
jsii-runtime-go
aws
Go
//go:build (go1.16 || go1.17) && !go1.18 // +build go1.16 go1.17 // +build !go1.18 package jsii import ( "fmt" "os" "github.com/aws/jsii-runtime-go/internal/compiler" "github.com/mattn/go-isatty" ) // / Emits a deprecation warning message when func init() { tty := isatty.IsTerminal(os.Stderr.Fd()) || isatty.IsCygwinTerminal(os.Stderr.Fd()) if tty { // Set terminal to bold red fmt.Fprintf(os.Stderr, "\u001b[31m\u001b[1m") } fmt.Fprintln(os.Stderr, "###########################################################") fmt.Fprintf(os.Stderr, "# This binary was compiled with %v, which has reached #\n", compiler.Version) fmt.Fprintf(os.Stderr, "# end-of-life on %v. #\n", compiler.EndOfLifeDate) fmt.Fprintln(os.Stderr, "# #") fmt.Fprintln(os.Stderr, "# Support for this version WILL be dropped in the future! #") fmt.Fprintln(os.Stderr, "# #") fmt.Fprintln(os.Stderr, "# See https://go.dev/security for more information. #") fmt.Fprintln(os.Stderr, "###########################################################") if tty { // Reset terminal back to normal fmt.Fprintf(os.Stderr, "\u001b[0m") } }
38
jsii-runtime-go
aws
Go
// Package jsii provides utilities that user code can leverage to facilitate // working with libraries generated by the `jsii-pacmak` tool. This includes // type conversion helpers as well as utilities to manage the runtime process' // lifecycle. package jsii
6
jsii-runtime-go
aws
Go
package jsii import "time" type basicType interface { bool | string | float64 | time.Time } // Ptr returns a pointer to the provided value. func Ptr[T basicType](v T) *T { return &v } // PtrSlice returns a pointer to a slice of pointers to all of the provided values. func PtrSlice[T basicType](v ...T) *[]*T { slice := make([]*T, len(v)) for i := 0; i < len(v); i++ { slice[i] = Ptr(v[i]) } return &slice } // Bool returns a pointer to the provided bool. func Bool(v bool) *bool { return Ptr(v) } // Bools returns a pointer to a slice of pointers to all of the provided booleans. func Bools(v ...bool) *[]*bool { return PtrSlice(v...) } type numberType interface { ~float32 | ~float64 | ~int | ~int8 | ~int16 | ~int32 | ~int64 | ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr } // Number returns a pointer to the provided float64. func Number[T numberType](v T) *float64 { return Ptr(float64(v)) } // Numbers returns a pointer to a slice of pointers to all of the provided numbers. func Numbers[T numberType](v ...T) *[]*float64 { slice := make([]*float64, len(v)) for i := 0; i < len(v); i++ { slice[i] = Number(v[i]) } return &slice } // String returns a pointer to the provided string. func String(v string) *string { return Ptr(v) } // Strings returns a pointer to a slice of pointers to all of the provided strings. func Strings(v ...string) *[]*string { return PtrSlice(v...) } // Time returns a pointer to the provided time.Time. func Time(v time.Time) *time.Time { return Ptr(v) } // Times returns a pointer to a slice of pointers to all of the provided time.Time values. func Times(v ...time.Time) *[]*time.Time { return PtrSlice(v...) }
66
jsii-runtime-go
aws
Go
package jsii import ( "testing" "time" "github.com/stretchr/testify/assert" ) func TestV(t *testing.T) { // Bool assert.Equal(t, true, *Ptr(true)) assert.Equal(t, false, *Ptr(false)) // Bools assert.Equal(t, []*bool{Bool(true), Bool(false), Bool(false), Bool(true)}, *PtrSlice(true, false, false, true)) // Float64 is supported because it doesn't require conversion. assert.Equal(t, 123.45, *Ptr(123.45)) assert.Equal(t, float64(123.45), *Ptr(float64(123.45))) // String assert.Equal(t, "Hello", *String("Hello")) // Strings assert.Equal(t, []*string{String("Hello"), String("World")}, *Strings("Hello", "World")) // Time now := time.Now() assert.Equal(t, now, *Time(now)) // Times assert.Equal(t, []*time.Time{Time(now)}, *Times(now)) } func TestBool(t *testing.T) { assert.Equal(t, true, *Bool(true)) assert.Equal(t, false, *Bool(false)) } func TestBools(t *testing.T) { assert.Equal(t, []*bool{Bool(true), Bool(false), Bool(false), Bool(true)}, *Bools(true, false, false, true)) } func TestNumber(t *testing.T) { assert.Equal(t, 123.45, *Number(123.45)) assert.Equal(t, 1337.0, *Number(1337)) // Floats. assert.Equal(t, float64(float32(123.45)), *Number(float32(123.45))) assert.Equal(t, float64(123.45), *Number(float64(123.45))) // Ints. assert.Equal(t, float64(1337), *Number(int(1337))) // Signed. assert.Equal(t, float64(127), *Number(int8(127))) assert.Equal(t, float64(1337), *Number(int16(1337))) assert.Equal(t, float64(1337), *Number(int32(1337))) assert.Equal(t, float64(1337), *Number(int64(1337))) // Unsigned. assert.Equal(t, float64(127), *Number(uint8(127))) assert.Equal(t, float64(1337), *Number(uint16(1337))) assert.Equal(t, float64(1337), *Number(uint32(1337))) assert.Equal(t, float64(1337), *Number(uint64(1337))) } func TestNumbers(t *testing.T) { assert.Equal(t, []*float64{Number(42), Number(1337)}, *Numbers(42, 1337)) } func TestString(t *testing.T) { assert.Equal(t, "Hello", *String("Hello")) } func TestStrings(t *testing.T) { assert.Equal(t, []*string{String("Hello"), String("World")}, *Strings("Hello", "World")) } func TestTime(t *testing.T) { now := time.Now() assert.Equal(t, now, *Time(now)) } func TestTimes(t *testing.T) { now := time.Now() assert.Equal(t, []*time.Time{Time(now)}, *Times(now)) }
80
jsii-runtime-go
aws
Go
package jsii import "github.com/aws/jsii-runtime-go/internal/kernel" // Close finalizes the runtime process, signalling the end of the execution to // the jsii kernel process, and waiting for graceful termination. The best // practice is to defer call thins at the beginning of the "main" function. func Close() { kernel.CloseClient() }
11
jsii-runtime-go
aws
Go
//go:build tools // +build tools // Package tools contains the necessary statements to ensure tool dependencies // are not "cleaned up" by "go mod tidy" despite being used... The "// +" // comment above makes sure the file is never included in an actual compiled // unit (unless someone manually specifies the "build tools" tag at compile // time). package tools import ( _ "golang.org/x/lint/golint" _ "golang.org/x/tools/cmd/godoc" _ "golang.org/x/tools/cmd/goimports" )
16
jsii-runtime-go
aws
Go
package api import ( "fmt" "regexp" ) // FQN represents a fully-qualified type name in the jsii type system. type FQN string // Override is a public interface implementing a private method `isOverride` // implemented by the private custom type `override`. This is embedded by // MethodOverride and PropertyOverride to simulate the union type of Override = // MethodOverride | PropertyOverride. type Override interface { GoName() string isOverride() } type override struct{} func (o override) isOverride() {} // MethodOverride is used to register a "go-native" implementation to be // substituted to the default javascript implementation on the created object. type MethodOverride struct { override JsiiMethod string `json:"method"` GoMethod string `json:"cookie"` } func (m MethodOverride) GoName() string { return m.GoMethod } // PropertyOverride is used to register a "go-native" implementation to be // substituted to the default javascript implementation on the created object. type PropertyOverride struct { override JsiiProperty string `json:"property"` GoGetter string `json:"cookie"` } func (m PropertyOverride) GoName() string { return m.GoGetter } func IsMethodOverride(value Override) bool { switch value.(type) { case MethodOverride, *MethodOverride: return true default: return false } } func IsPropertyOverride(value Override) bool { switch value.(type) { case PropertyOverride, *PropertyOverride: return true default: return false } } type ObjectRef struct { InstanceID string `json:"$jsii.byref"` Interfaces []FQN `json:"$jsii.interfaces,omitempty"` } func (o *ObjectRef) TypeFQN() FQN { re := regexp.MustCompile(`^(.+)@(\d+)$`) if parts := re.FindStringSubmatch(o.InstanceID); parts == nil { panic(fmt.Errorf("invalid instance id: %#v", o.InstanceID)) } else { return FQN(parts[1]) } } type EnumRef struct { MemberFQN string `json:"$jsii.enum"` } type WireDate struct { Timestamp string `json:"$jsii.date"` } type WireMap struct { MapData map[string]interface{} `json:"$jsii.map"` } type WireStruct struct { StructDescriptor `json:"$jsii.struct"` } type StructDescriptor struct { FQN FQN `json:"fqn"` Fields map[string]interface{} `json:"data"` }
102
jsii-runtime-go
aws
Go
// Package api contains shared type definisions used by several modules part of // the jsii runtime for go. It helps avoid creating circular dependencies // between the other modules. package api
5
jsii-runtime-go
aws
Go
//go:build go1.16 && !go1.17 // +build go1.16,!go1.17 package compiler // Version denotes the version of the go compiler that was used for building // this binary. It is intended for use only in the compiler deprecation warning // message. const Version = "go1.16" // EndOfLifeDate is the date at which this compiler version reached end-of-life. const EndOfLifeDate = "2022-03-15"
13
jsii-runtime-go
aws
Go
//go:build go1.17 && !go1.18 // +build go1.17,!go1.18 package compiler // Version denotes the version of the go compiler that was used for building // this binary. It is intended for use only in the compiler deprecation warning // message. const Version = "go1.17" // EndOfLifeDate is the date at which this compiler version reached end-of-life. const EndOfLifeDate = "2022-08-02"
13
jsii-runtime-go
aws
Go
// Package embedded contains the embedded @jsii/kernel code, which is used // unless the JSII_RUNTIME environment variable is set to a different program. package embedded
4
jsii-runtime-go
aws
Go
package embedded import ( "embed" "os" "path" ) // embeddedRootDir is the name of the root directory for the embeddedFS variable. const embeddedRootDir string = "resources" //go:embed resources/* var embeddedFS embed.FS // entrypointName is the path to the entry point relative to the embeddedRootDir. var entrypointName = path.Join("bin", "jsii-runtime.js") // ExtractRuntime extracts a copy of the embedded runtime library into // the designated directory, and returns the fully qualified path to the entry // point to be used when starting the child process. func ExtractRuntime(into string) (entrypoint string, err error) { err = extractRuntime(into, embeddedRootDir) if err == nil { entrypoint = path.Join(into, entrypointName) } return } // extractRuntime copies the contents of embeddedFS at "from" to the provided // "into" directory, recursively. func extractRuntime(into string, from string) error { files, err := embeddedFS.ReadDir(from) if err != nil { return err } for _, file := range files { src := path.Join(from, file.Name()) dest := path.Join(into, file.Name()) if file.IsDir() { if err = os.Mkdir(dest, 0o700); err != nil { return err } if err = extractRuntime(dest, src); err != nil { return err } } else { data, err := embeddedFS.ReadFile(src) if err != nil { return err } if err = os.WriteFile(dest, data, 0o600); err != nil { return err } } } return nil }
58
jsii-runtime-go
aws
Go
package embedded import ( "path" "testing" ) func TestEntryPointExists(t *testing.T) { if bytes, err := embeddedFS.ReadFile(path.Join(embeddedRootDir, entrypointName)); err != nil { t.Errorf("unable to read entry point data: %v", err) } else if len(bytes) == 0 { t.Error("entry point file is empty") } }
16
jsii-runtime-go
aws
Go
package kernel import ( "github.com/aws/jsii-runtime-go/internal/api" ) type BeginProps struct { Method *string `json:"method"` Arguments []interface{} `json:"args"` ObjRef api.ObjectRef `json:"objref"` } type BeginResponse struct { kernelResponse PromiseID *string `json:"promise_id"` } func (c *Client) Begin(props BeginProps) (response BeginResponse, err error) { type request struct { kernelRequest BeginProps } err = c.request(request{kernelRequest{"begin"}, props}, &response) return }
26
jsii-runtime-go
aws
Go
package kernel import ( "fmt" "reflect" "strings" "github.com/aws/jsii-runtime-go/internal/api" ) type callback struct { CallbackID string `json:"cbid"` Cookie string `json:"cookie"` Invoke *invokeCallback `json:"invoke"` Get *getCallback `json:"get"` Set *setCallback `json:"set"` } func (c *callback) handle(result kernelResponder) error { var ( retval reflect.Value err error ) if c.Invoke != nil { retval, err = c.Invoke.handle(c.Cookie) } else if c.Get != nil { retval, err = c.Get.handle(c.Cookie) } else if c.Set != nil { retval, err = c.Set.handle(c.Cookie) } else { return fmt.Errorf("invalid callback object: %v", c) } if err != nil { return err } type callbackResult struct { CallbackID string `json:"cbid"` Result interface{} `json:"result,omitempty"` Error string `json:"err,omitempty"` } type completeRequest struct { kernelRequester callbackResult `json:"complete"` } client := GetClient() request := completeRequest{} request.CallbackID = c.CallbackID request.Result = client.CastPtrToRef(retval) if err != nil { request.Error = err.Error() } return client.request(request, result) } type invokeCallback struct { Method string `json:"method"` Arguments []interface{} `json:"args"` ObjRef api.ObjectRef `json:"objref"` } func (i *invokeCallback) handle(cookie string) (retval reflect.Value, err error) { client := GetClient() receiver := reflect.ValueOf(client.GetObject(i.ObjRef)) method := receiver.MethodByName(cookie) return client.invoke(method, i.Arguments) } type getCallback struct { Property string `json:"property"` ObjRef api.ObjectRef `json:"objref"` } func (g *getCallback) handle(cookie string) (retval reflect.Value, err error) { client := GetClient() receiver := reflect.ValueOf(client.GetObject(g.ObjRef)) if strings.HasPrefix(cookie, ".") { // Ready to catch an error if the access panics... defer func() { if r := recover(); r != nil { if err == nil { var ok bool if err, ok = r.(error); !ok { err = fmt.Errorf("%v", r) } } else { // This is not expected - so we panic! panic(r) } } }() // Need to access the underlying struct... receiver = receiver.Elem() retval = receiver.FieldByName(cookie[1:]) if retval.IsZero() { // Omit zero-values if a json tag instructs so... field, _ := receiver.Type().FieldByName(cookie[1:]) if tag := field.Tag.Get("json"); tag != "" { for _, attr := range strings.Split(tag, ",")[1:] { if attr == "omitempty" { retval = reflect.ValueOf(nil) break } } } } return } else { method := receiver.MethodByName(cookie) return client.invoke(method, nil) } } type setCallback struct { Property string `json:"property"` Value interface{} `json:"value"` ObjRef api.ObjectRef `json:"objref"` } func (s *setCallback) handle(cookie string) (retval reflect.Value, err error) { client := GetClient() receiver := reflect.ValueOf(client.GetObject(s.ObjRef)) if strings.HasPrefix(cookie, ".") { // Ready to catch an error if the access panics... defer func() { if r := recover(); r != nil { if err == nil { var ok bool if err, ok = r.(error); !ok { err = fmt.Errorf("%v", r) } } else { // This is not expected - so we panic! panic(r) } } }() // Need to access the underlying struct... receiver = receiver.Elem() field := receiver.FieldByName(cookie[1:]) meta, _ := receiver.Type().FieldByName(cookie[1:]) field.Set(convert(reflect.ValueOf(s.Value), meta.Type)) // Both retval & err are set to zero values here... return } else { method := receiver.MethodByName(fmt.Sprintf("Set%v", cookie)) return client.invoke(method, []interface{}{s.Value}) } } func convert(value reflect.Value, typ reflect.Type) reflect.Value { retry: vt := value.Type() if vt.AssignableTo(typ) { return value } if value.CanConvert(typ) { return value.Convert(typ) } if typ.Kind() == reflect.Ptr { switch value.Kind() { case reflect.String: str := value.String() value = reflect.ValueOf(&str) case reflect.Bool: bool := value.Bool() value = reflect.ValueOf(&bool) case reflect.Int: int := value.Int() value = reflect.ValueOf(&int) case reflect.Float64: float := value.Float() value = reflect.ValueOf(&float) default: iface := value.Interface() value = reflect.ValueOf(&iface) } goto retry } // Unsure what to do... let default behavior happen... return value } func (c *Client) invoke(method reflect.Value, args []interface{}) (retval reflect.Value, err error) { if !method.IsValid() { err = fmt.Errorf("invalid method") return } // Convert the arguments, if any... callArgs := make([]reflect.Value, len(args)) methodType := method.Type() numIn := methodType.NumIn() for i, arg := range args { var argType reflect.Type if i < numIn { argType = methodType.In(i) } else if methodType.IsVariadic() { argType = methodType.In(i - 1) } else { err = fmt.Errorf("too many arguments received %d for %d", len(args), numIn) return } if argType.Kind() == reflect.Ptr { callArgs[i] = reflect.New(argType.Elem()) } else { callArgs[i] = reflect.New(argType) } c.castAndSetToPtr(callArgs[i].Elem(), reflect.ValueOf(arg)) if argType.Kind() != reflect.Ptr { // The result of `reflect.New` is always a pointer, so if the // argument is by-value, we have to de-reference it first. callArgs[i] = callArgs[i].Elem() } } // Ready to catch an error if the method panics... defer func() { if r := recover(); r != nil { if err == nil { var ok bool if err, ok = r.(error); !ok { err = fmt.Errorf("%v", r) } } else { // This is not expected - so we panic! panic(r) } } }() result := method.Call(callArgs) switch len(result) { case 0: // Nothing to do, retval is already a 0-value. case 1: retval = result[0] default: err = fmt.Errorf("too many return values: %v", result) } return }
258
jsii-runtime-go
aws
Go
package kernel import ( "fmt" "reflect" "runtime" "sync" "github.com/aws/jsii-runtime-go/internal/api" "github.com/aws/jsii-runtime-go/internal/kernel/process" "github.com/aws/jsii-runtime-go/internal/objectstore" "github.com/aws/jsii-runtime-go/internal/typeregistry" ) var ( clientInstance *Client clientInstanceMutex sync.Mutex clientOnce sync.Once types *typeregistry.TypeRegistry = typeregistry.New() ) // The Client struct owns the jsii child process and its io interfaces. It also // owns a map (objects) that tracks all object references by ID. This is used // to call methods and access properties on objects passed by the runtime // process by reference. type Client struct { process *process.Process objects *objectstore.ObjectStore // Supports the idempotency of the Load method. loaded map[LoadProps]LoadResponse } // GetClient returns a singleton Client instance, initializing one the first // time it is called. func GetClient() *Client { clientOnce.Do(func() { // Locking early to be safe with a concurrent Close execution clientInstanceMutex.Lock() defer clientInstanceMutex.Unlock() client, err := newClient() if err != nil { panic(err) } clientInstance = client }) return clientInstance } // CloseClient finalizes the runtime process, signalling the end of the // execution to the jsii kernel process, and waiting for graceful termination. // // If a jsii Client is used *after* CloseClient was called, a new jsii kernel // process will be initialized, and CloseClient should be called again to // correctly finalize that, too. func CloseClient() { // Locking early to be safe with a concurrent getClient execution clientInstanceMutex.Lock() defer clientInstanceMutex.Unlock() // Reset the "once" so a new Client would get initialized next time around clientOnce = sync.Once{} if clientInstance != nil { // Close the Client & reset it clientInstance.close() clientInstance = nil } } // newClient initializes a client, making it ready for business. func newClient() (*Client, error) { if process, err := process.NewProcess(fmt.Sprintf("^%v", version)); err != nil { return nil, err } else { result := &Client{ process: process, objects: objectstore.New(), loaded: make(map[LoadProps]LoadResponse), } // Register a finalizer to call Close() runtime.SetFinalizer(result, func(c *Client) { c.close() }) return result, nil } } func (c *Client) Types() *typeregistry.TypeRegistry { return types } func (c *Client) RegisterInstance(instance reflect.Value, objectRef api.ObjectRef) error { return c.objects.Register(instance, objectRef) } func (c *Client) request(req kernelRequester, res kernelResponder) error { return c.process.Request(req, res) } func (c *Client) FindObjectRef(obj reflect.Value) (ref api.ObjectRef, found bool) { ref = api.ObjectRef{} found = false switch obj.Kind() { case reflect.Struct: // Structs can be checked only if they are addressable, meaning // they are obtained from fields of an addressable struct. if !obj.CanAddr() { return } obj = obj.Addr() fallthrough case reflect.Interface, reflect.Ptr: if ref.InstanceID, found = c.objects.InstanceID(obj); found { ref.Interfaces = c.objects.Interfaces(ref.InstanceID) } return default: // Other types cannot possibly be object references! return } } func (c *Client) GetObject(objref api.ObjectRef) interface{} { if obj, ok := c.objects.GetObject(objref.InstanceID); ok { return obj.Interface() } panic(fmt.Errorf("no object found for ObjectRef %v", objref)) } func (c *Client) close() { c.process.Close() // We no longer need a finalizer to run runtime.SetFinalizer(c, nil) }
143
jsii-runtime-go
aws
Go
package kernel import ( "reflect" "testing" "github.com/aws/jsii-runtime-go/internal/typeregistry" ) func TestClient(t *testing.T) { client, err := newClient() if err != nil { t.Fatalf("client init failed: %v", err.Error()) } defer client.close() t.Run("Client Load Error", func(t *testing.T) { request := LoadProps{ Name: "jsii-calc", Version: "0.0.0", } res, err := client.Load(request, nil) t.Log(res) if err != nil { t.Log(err) } }) t.Run("Type registry survives CloseClient()", func(t *testing.T) { client, err := newClient() if err != nil { t.Fatalf("client init failed: %v", err.Error()) } // Clean up after ourselves, so this test does not leave traces behind. defer func() { types = typeregistry.New() }() type enumType string var enumTypeFOO enumType = "FOO" registry := client.Types() err = registry.RegisterEnum( "example.Enum", reflect.TypeOf((*enumType)(nil)).Elem(), map[string]interface{}{"FOO": enumTypeFOO}, ) if err != nil { t.Fatalf("failed registering enum: %v", err.Error()) } CloseClient() // Getting the registry from the client again. registry = client.Types() if _, ok := registry.TryRenderEnumRef(reflect.ValueOf(enumTypeFOO)); !ok { t.Errorf("failed rendering enum ref, it should have worked!") } }) }
63
jsii-runtime-go
aws
Go
package kernel type CompleteProps struct { CallbackID *string `json:"cbid"` Error *string `json:"err"` Result interface{} `json:"result"` } type CompleteResponse struct { kernelResponse CallbackID *string `json:"cbid"` } func (c *Client) Complete(props CompleteProps) (response CompleteResponse, err error) { type request struct { kernelRequest CompleteProps } err = c.request(request{kernelRequest{"complete"}, props}, &response) return }
22
jsii-runtime-go
aws
Go
package kernel import ( "fmt" "reflect" "time" "github.com/aws/jsii-runtime-go/internal/api" ) var ( anyType = reflect.TypeOf((*interface{})(nil)).Elem() ) // CastAndSetToPtr accepts a pointer to any type and attempts to cast the value // argument to be the same type. Then it sets the value of the pointer element // to be the newly cast data. This is used to cast payloads from JSII to // expected return types for Get and Invoke functions. func (c *Client) CastAndSetToPtr(ptr interface{}, data interface{}) { ptrVal := reflect.ValueOf(ptr).Elem() dataVal := reflect.ValueOf(data) c.castAndSetToPtr(ptrVal, dataVal) } // castAndSetToPtr is the same as CastAndSetToPtr except it operates on the // reflect.Value representation of the pointer and data. func (c *Client) castAndSetToPtr(ptr reflect.Value, data reflect.Value) { if !data.IsValid() { // data will not be valid if was made from a nil value, as there would // not have been enough type information available to build a valid // reflect.Value. In such cases, we must craft the correctly-typed zero // value ourselves. data = reflect.Zero(ptr.Type()) } else if ptr.Kind() == reflect.Ptr && ptr.IsNil() { // if ptr is a Pointer type and data is valid, initialize a non-nil pointer // type. Otherwise inner value is not-settable upon recursion. See third // law of reflection. // https://blog.golang.org/laws-of-reflection ptr.Set(reflect.New(ptr.Type().Elem())) c.castAndSetToPtr(ptr.Elem(), data) return } else if data.Kind() == reflect.Interface && !data.IsNil() { // If data is a non-nil interface, unwrap it to get it's dynamic value // type sorted out, so that further calls in this method don't have to // worry about this edge-case when reasoning on kinds. data = reflect.ValueOf(data.Interface()) } if ref, isRef := castValToRef(data); isRef { // If return data is a jsii struct passed by reference, de-reference it all. if fields, _, isStruct := c.Types().StructFields(ptr.Type()); isStruct { for _, field := range fields { got, err := c.Get(GetProps{ Property: field.Tag.Get("json"), ObjRef: ref, }) if err != nil { panic(err) } fieldVal := ptr.FieldByIndex(field.Index) c.castAndSetToPtr(fieldVal, reflect.ValueOf(got.Value)) } return } targetType := ptr.Type() if typ, ok := c.Types().FindType(ref.TypeFQN()); ok && typ.AssignableTo(ptr.Type()) { // Specialize the return type to be the dynamic value type targetType = typ } // If it's currently tracked, return the current instance if object, ok := c.objects.GetObjectAs(ref.InstanceID, targetType); ok { ptr.Set(object) return } // If return data is jsii object references, add to objects table. if err := c.Types().InitJsiiProxy(ptr, targetType); err == nil { if err = c.RegisterInstance(ptr, ref); err != nil { panic(err) } } else { panic(err) } return } if enumref, isEnum := castValToEnumRef(data); isEnum { member, err := c.Types().EnumMemberForEnumRef(enumref) if err != nil { panic(err) } ptr.Set(reflect.ValueOf(member)) return } if date, isDate := castValToDate(data); isDate { ptr.Set(reflect.ValueOf(date)) return } // maps if m, isMap := c.castValToMap(data, ptr.Type()); isMap { ptr.Set(m) return } // arrays if data.Kind() == reflect.Slice { len := data.Len() var slice reflect.Value if ptr.Kind() == reflect.Slice { slice = reflect.MakeSlice(ptr.Type(), len, len) } else { slice = reflect.MakeSlice(reflect.SliceOf(anyType), len, len) } // If return type is a slice, recursively cast elements for i := 0; i < len; i++ { c.castAndSetToPtr(slice.Index(i), data.Index(i)) } ptr.Set(slice) return } ptr.Set(data) } // Accepts pointers to structs that implement interfaces and searches for an // existing object reference in the kernel. If it exists, it casts it to an // objref for the runtime. Recursively casts types that may contain nested // object references. func (c *Client) CastPtrToRef(dataVal reflect.Value) interface{} { if !dataVal.IsValid() { // dataVal is a 0-value, meaning we have no value available... We return // this to JavaScript as a "null" value. return nil } if (dataVal.Kind() == reflect.Interface || dataVal.Kind() == reflect.Ptr) && dataVal.IsNil() { return nil } // In case we got a time.Time value (or pointer to one). if wireDate, isDate := castPtrToDate(dataVal); isDate { return wireDate } switch dataVal.Kind() { case reflect.Map: result := api.WireMap{MapData: make(map[string]interface{})} iter := dataVal.MapRange() for iter.Next() { key := iter.Key().String() val := iter.Value() result.MapData[key] = c.CastPtrToRef(val) } return result case reflect.Interface, reflect.Ptr: if valref, valHasRef := c.FindObjectRef(dataVal); valHasRef { return valref } // In case we got a pointer to a map, slice, enum, ... if elem := reflect.Indirect(dataVal.Elem()); elem.Kind() != reflect.Struct { return c.CastPtrToRef(elem) } if dataVal.Elem().Kind() == reflect.Struct { elemVal := dataVal.Elem() if fields, fqn, isStruct := c.Types().StructFields(elemVal.Type()); isStruct { data := make(map[string]interface{}) for _, field := range fields { fieldVal := elemVal.FieldByIndex(field.Index) if (fieldVal.Kind() == reflect.Ptr || fieldVal.Kind() == reflect.Interface) && fieldVal.IsNil() { // If there is the "field" tag, and it's "required", then panic since the value is nil. if requiredOrOptional, found := field.Tag.Lookup("field"); found && requiredOrOptional == "required" { panic(fmt.Sprintf("Field %v.%v is required, but has nil value", field.Type, field.Name)) } continue } key := field.Tag.Get("json") data[key] = c.CastPtrToRef(fieldVal) } return api.WireStruct{ StructDescriptor: api.StructDescriptor{ FQN: fqn, Fields: data, }, } } } else if dataVal.Elem().Kind() == reflect.Ptr { // Typically happens when a struct pointer is passed into an interface{} // typed API (such as a place where a union is accepted). elemVal := dataVal.Elem() return c.CastPtrToRef(elemVal) } if ref, err := c.ManageObject(dataVal); err != nil { panic(err) } else { return ref } case reflect.Slice: refs := make([]interface{}, dataVal.Len()) for i := 0; i < dataVal.Len(); i++ { refs[i] = c.CastPtrToRef(dataVal.Index(i)) } return refs case reflect.String: if enumRef, isEnumRef := c.Types().TryRenderEnumRef(dataVal); isEnumRef { return enumRef } } return dataVal.Interface() } // castPtrToDate obtains an api.WireDate from the provided reflect.Value if it // represents a time.Time or *time.Time value. It accepts both a pointer and // direct value as a convenience (when passing time.Time through an interface{} // parameter, having to unwrap it as a pointer is annoying and unneeded). func castPtrToDate(data reflect.Value) (wireDate api.WireDate, ok bool) { var timestamp *time.Time if timestamp, ok = data.Interface().(*time.Time); !ok { var val time.Time if val, ok = data.Interface().(time.Time); ok { timestamp = &val } } if ok { wireDate.Timestamp = timestamp.Format(time.RFC3339Nano) } return } func castValToRef(data reflect.Value) (ref api.ObjectRef, ok bool) { if data.Kind() == reflect.Map { for _, k := range data.MapKeys() { // Finding values type requires extracting from reflect.Value // otherwise .Kind() returns `interface{}` v := reflect.ValueOf(data.MapIndex(k).Interface()) if k.Kind() != reflect.String { continue } switch k.String() { case "$jsii.byref": if v.Kind() != reflect.String { ok = false return } ref.InstanceID = v.String() ok = true case "$jsii.interfaces": if v.Kind() != reflect.Slice { continue } ifaces := make([]api.FQN, v.Len()) for i := 0; i < v.Len(); i++ { e := reflect.ValueOf(v.Index(i).Interface()) if e.Kind() != reflect.String { ok = false return } ifaces[i] = api.FQN(e.String()) } ref.Interfaces = ifaces } } } return ref, ok } // TODO: This should return a time.Time instead func castValToDate(data reflect.Value) (date time.Time, ok bool) { if data.Kind() == reflect.Map { for _, k := range data.MapKeys() { v := reflect.ValueOf(data.MapIndex(k).Interface()) if k.Kind() == reflect.String && k.String() == "$jsii.date" && v.Kind() == reflect.String { var err error date, err = time.Parse(time.RFC3339Nano, v.String()) ok = (err == nil) break } } } return } func castValToEnumRef(data reflect.Value) (enum api.EnumRef, ok bool) { ok = false if data.Kind() == reflect.Map { for _, k := range data.MapKeys() { // Finding values type requires extracting from reflect.Value // otherwise .Kind() returns `interface{}` v := reflect.ValueOf(data.MapIndex(k).Interface()) if k.Kind() == reflect.String && k.String() == "$jsii.enum" && v.Kind() == reflect.String { enum.MemberFQN = v.String() ok = true break } } } return } // castValToMap attempts converting the provided jsii wire value to a // go map. This recognizes the "$jsii.map" object and does the necessary // recursive value conversion. func (c *Client) castValToMap(data reflect.Value, mapType reflect.Type) (m reflect.Value, ok bool) { ok = false if data.Kind() != reflect.Map || data.Type().Key().Kind() != reflect.String { return } if mapType.Kind() == reflect.Map && mapType.Key().Kind() != reflect.String { return } if mapType == anyType { mapType = reflect.TypeOf((map[string]interface{})(nil)) } dataIter := data.MapRange() for dataIter.Next() { key := dataIter.Key().String() if key != "$jsii.map" { continue } // Finding value type requries extracting from reflect.Value // otherwise .Kind() returns `interface{}` val := reflect.ValueOf(dataIter.Value().Interface()) if val.Kind() != reflect.Map { return } ok = true m = reflect.MakeMap(mapType) iter := val.MapRange() for iter.Next() { val := iter.Value() // Note: reflect.New(t) returns a pointer to a newly allocated t convertedVal := reflect.New(mapType.Elem()).Elem() c.castAndSetToPtr(convertedVal, val) m.SetMapIndex(iter.Key(), convertedVal) } return } return }
371
jsii-runtime-go
aws
Go
package kernel import "github.com/aws/jsii-runtime-go/internal/api" type CreateProps struct { FQN api.FQN `json:"fqn"` Interfaces []api.FQN `json:"interfaces,omitempty"` Arguments []interface{} `json:"args,omitempty"` Overrides []api.Override `json:"overrides,omitempty"` } // TODO extends AnnotatedObjRef? type CreateResponse struct { kernelResponse InstanceID string `json:"$jsii.byref"` } func (c *Client) Create(props CreateProps) (response CreateResponse, err error) { type request struct { kernelRequest CreateProps } err = c.request(request{kernelRequest{"create"}, props}, &response) return } // UnmarshalJSON provides custom unmarshalling implementation for response // structs. Creating new types is required in order to avoid infinite recursion. func (r *CreateResponse) UnmarshalJSON(data []byte) error { type response CreateResponse return unmarshalKernelResponse(data, (*response)(r), r) }
33
jsii-runtime-go
aws
Go
package kernel import "github.com/aws/jsii-runtime-go/internal/api" type DelProps struct { ObjRef api.ObjectRef `json:"objref"` } type DelResponse struct { kernelResponse } func (c *Client) Del(props DelProps) (response DelResponse, err error) { type request struct { kernelRequest DelProps } err = c.request(request{kernelRequest{"del"}, props}, &response) return }
21
jsii-runtime-go
aws
Go
// Package kernel defines the interface for go programs to interact with the // @jsii/kernel node process. This module completely abstracts managament of the // child process. package kernel
5
jsii-runtime-go
aws
Go
package kernel type EndProps struct { PromiseID *string `json:"promise_id"` } type EndResponse struct { kernelResponse Result interface{} `json:"result"` } func (c *Client) End(props EndProps) (response EndResponse, err error) { type request struct { kernelRequest EndProps } err = c.request(request{kernelRequest{"end"}, props}, &response) return }
20
jsii-runtime-go
aws
Go
package kernel import "github.com/aws/jsii-runtime-go/internal/api" type GetProps struct { Property string `json:"property"` ObjRef api.ObjectRef `json:"objref"` } type StaticGetProps struct { FQN api.FQN `json:"fqn"` Property string `json:"property"` } type GetResponse struct { kernelResponse Value interface{} `json:"value"` } func (c *Client) Get(props GetProps) (response GetResponse, err error) { type request struct { kernelRequest GetProps } err = c.request(request{kernelRequest{"get"}, props}, &response) return } func (c *Client) SGet(props StaticGetProps) (response GetResponse, err error) { type request struct { kernelRequest StaticGetProps } err = c.request(request{kernelRequest{"sget"}, props}, &response) return } // UnmarshalJSON provides custom unmarshalling implementation for response // structs. Creating new types is required in order to avoid infinite recursion. func (r *GetResponse) UnmarshalJSON(data []byte) error { type response GetResponse return unmarshalKernelResponse(data, (*response)(r), r) }
44
jsii-runtime-go
aws
Go
package kernel import "github.com/aws/jsii-runtime-go/internal/api" type InvokeProps struct { Method string `json:"method"` Arguments []interface{} `json:"args"` ObjRef api.ObjectRef `json:"objref"` } type StaticInvokeProps struct { FQN api.FQN `json:"fqn"` Method string `json:"method"` Arguments []interface{} `json:"args"` } type InvokeResponse struct { kernelResponse Result interface{} `json:"result"` } func (c *Client) Invoke(props InvokeProps) (response InvokeResponse, err error) { type request struct { kernelRequest InvokeProps } err = c.request(request{kernelRequest{"invoke"}, props}, &response) return } func (c *Client) SInvoke(props StaticInvokeProps) (response InvokeResponse, err error) { type request struct { kernelRequest StaticInvokeProps } err = c.request(request{kernelRequest{"sinvoke"}, props}, &response) return } // UnmarshalJSON provides custom unmarshalling implementation for response // structs. Creating new types is required in order to avoid infinite recursion. func (r *InvokeResponse) UnmarshalJSON(data []byte) error { type response InvokeResponse return unmarshalKernelResponse(data, (*response)(r), r) }
46
jsii-runtime-go
aws
Go
package kernel import ( "encoding/json" "errors" ) // unmarshalKernelResponse performs custom unmarshaling for kernel responses, checks for presence of `error` key on json // and returns if present. // // The uresult parameter may be passed to json.Unmarshal so if unmarshalKernelResponse is called within a custom // UnmarshalJSON function, it must be a type alias (otherwise, this will recurse into itself until the stack is full). // The result parameter must point to the original result (with the original type). This unfortunate duplication is // necessary for the proper handling of in-line callbacks. func unmarshalKernelResponse(data []byte, uresult kernelResponder, result kernelResponder) error { datacopy := make([]byte, len(data)) copy(datacopy, data) var response map[string]json.RawMessage if err := json.Unmarshal(datacopy, &response); err != nil { return err } if err, ok := response["error"]; ok { return errors.New(string(err)) } // In-line callback requests interrupt the current flow, the callback handling // logic will resume this handling once the callback request has been fulfilled. if raw, ok := response["callback"]; ok { callback := callback{} if err := json.Unmarshal(raw, &callback); err != nil { return err } return callback.handle(result) } return json.Unmarshal(response["ok"], uresult) }
41
jsii-runtime-go
aws
Go
package kernel import ( "fmt" "io/ioutil" "os" "regexp" ) // LoadProps holds the necessary information to load a library into the // @jsii/kernel process through the Load method. type LoadProps struct { Name string `json:"name"` Version string `json:"version"` } // LoadResponse contains the data returned by the @jsii/kernel process in // response to a load request. type LoadResponse struct { kernelResponse Assembly string `json:"assembly"` Types float64 `json:"types"` } // Load ensures the specified assembly has been loaded into the @jsii/kernel // process. This call is idempotent (calling it several times with the same // input results in the same output). func (c *Client) Load(props LoadProps, tarball []byte) (response LoadResponse, err error) { if response, cached := c.loaded[props]; cached { return response, nil } tmpfile, err := ioutil.TempFile("", fmt.Sprintf( "%v-%v.*.tgz", regexp.MustCompile("[^a-zA-Z0-9_-]").ReplaceAllString(props.Name, "-"), version, )) if err != nil { return } defer os.Remove(tmpfile.Name()) if _, err := tmpfile.Write(tarball); err != nil { panic(err) } tmpfile.Close() type request struct { kernelRequest LoadProps Tarball string `json:"tarball"` } err = c.request(request{kernelRequest{"load"}, props, tmpfile.Name()}, &response) if err == nil { c.loaded[props] = response } return } // UnmarshalJSON provides custom unmarshalling implementation for response // structs. Creating new types is required in order to avoid infinite recursion. func (r *LoadResponse) UnmarshalJSON(data []byte) error { type response LoadResponse return unmarshalKernelResponse(data, (*response)(r), r) }
67
jsii-runtime-go
aws
Go
package kernel import ( "fmt" "reflect" "strings" "github.com/aws/jsii-runtime-go/internal/api" ) const objectFQN = "Object" func (c *Client) ManageObject(v reflect.Value) (ref api.ObjectRef, err error) { // Ensuring we use a pointer, so we can see pointer-receiver methods, too. var vt reflect.Type if v.Kind() == reflect.Interface || (v.Kind() == reflect.Ptr && v.Elem().Kind() == reflect.Interface) { vt = reflect.Indirect(reflect.ValueOf(v.Interface())).Addr().Type() } else { vt = reflect.Indirect(v).Addr().Type() } interfaces, overrides := c.Types().DiscoverImplementation(vt) found := make(map[string]bool) for _, override := range overrides { if prop, ok := override.(*api.PropertyOverride); ok { found[prop.JsiiProperty] = true } } overrides = appendExportedProperties(vt, overrides, found) var resp CreateResponse resp, err = c.Create(CreateProps{ FQN: objectFQN, Interfaces: interfaces, Overrides: overrides, }) if err == nil { if err = c.objects.Register(v, api.ObjectRef{InstanceID: resp.InstanceID, Interfaces: interfaces}); err == nil { ref.InstanceID = resp.InstanceID } } return } func appendExportedProperties(vt reflect.Type, overrides []api.Override, found map[string]bool) []api.Override { if vt.Kind() == reflect.Ptr { vt = vt.Elem() } if vt.Kind() == reflect.Struct { for idx := 0; idx < vt.NumField(); idx++ { field := vt.Field(idx) // Unexported fields are not relevant here... if !field.IsExported() { continue } // Anonymous fields are embed, we traverse them for fields, too... if field.Anonymous { overrides = appendExportedProperties(field.Type, overrides, found) continue } jsonName := field.Tag.Get("json") if jsonName == "-" { // Explicit omit via `json:"-"` continue } else if jsonName != "" { // There could be attributes after the field name (e.g. `json:"foo,omitempty"`) jsonName = strings.Split(jsonName, ",")[0] } // The default behavior is to use the field name as-is in JSON. if jsonName == "" { jsonName = field.Name } if !found[jsonName] { overrides = append(overrides, &api.PropertyOverride{ JsiiProperty: jsonName, // Using the "." prefix to signify this isn't actually a getter, just raw field access. GoGetter: fmt.Sprintf(".%s", field.Name), }) found[jsonName] = true } } } return overrides }
92
jsii-runtime-go
aws
Go
package kernel type NamingProps struct { Assembly string `json:"assembly"` } type NamingResponse struct { kernelResponse // readonly naming: { // readonly [language: string]: { readonly [key: string]: any } | undefined; // }; } func (c *Client) Naming(props NamingProps) (response NamingResponse, err error) { type request struct { kernelRequest NamingProps } err = c.request(request{kernelRequest{"naming"}, props}, &response) return }
22
jsii-runtime-go
aws
Go
package kernel // kernelRequester allows creating a union of kernelRequester and kernelResponder // types by defining private method implemented by a private custom type, which // is embedded in all relevant types. type kernelRequester interface { // isRequest is a marker method that is intended to ensure no external type // can implement this interface. isRequest() kernelBrand } // kernelRequest is the standard implementation for kernelRequester. type kernelRequest struct { API string `json:"api"` } func (r kernelRequest) isRequest() kernelBrand { return kernelBrand{} } // kernelResponder allows creating a union of kernelResponder and kernelRequester // types by defining private method implemented by a private custom type, which // is embedded in all relevant types. type kernelResponder interface { // isResponse is a marker method that is intended to ensure no external type // can implement this interface. isResponse() kernelBrand } // kernelResponse is a 0-width marker struc tembedded to make another type be // usable as a kernelResponder. type kernelResponse struct{} func (r kernelResponse) isResponse() kernelBrand { return kernelBrand{} } // kernelBrand is a private type used to ensure the kernelRequester and // kernelResponder cannot be implemented outside of this package. type kernelBrand struct{}
41
jsii-runtime-go
aws
Go
package kernel import "github.com/aws/jsii-runtime-go/internal/api" type SetProps struct { Property string `json:"property"` Value interface{} `json:"value"` ObjRef api.ObjectRef `json:"objref"` } type StaticSetProps struct { FQN api.FQN `json:"fqn"` Property string `json:"property"` Value interface{} `json:"value"` } type SetResponse struct { kernelResponse } func (c *Client) Set(props SetProps) (response SetResponse, err error) { type request struct { kernelRequest SetProps } err = c.request(request{kernelRequest{"set"}, props}, &response) return } func (c *Client) SSet(props StaticSetProps) (response SetResponse, err error) { type request struct { kernelRequest StaticSetProps } err = c.request(request{kernelRequest{"sset"}, props}, &response) return } // UnmarshalJSON provides custom unmarshalling implementation for response // structs. Creating new types is required in order to avoid infinite recursion. func (r *SetResponse) UnmarshalJSON(data []byte) error { type response SetResponse return unmarshalKernelResponse(data, (*response)(r), r) }
45
jsii-runtime-go
aws
Go
package kernel type StatsResponse struct { kernelResponse ObjectCount float64 `json:"object_count"` } func (c *Client) Stats() (response StatsResponse, err error) { err = c.request(kernelRequest{"stats"}, &response) return }
12
jsii-runtime-go
aws
Go
package kernel const version = "1.84.0"
4
jsii-runtime-go
aws
Go
package process import ( "bufio" "encoding/json" "io" "os" ) type consoleMessage struct { Stderr []byte `json:"stderr"` Stdout []byte `json:"stdout"` } // consumeStderr is intended to be used as a goroutine, and will consume this // process' stderr stream until it reaches EOF. It reads the stream line-by-line // and will decode any console messages per the jsii wire protocol specification. // Once EOF has been reached, true will be sent to the done channel, allowing // other goroutines to check whether the goroutine has reached EOF (and hence // finished) or not. func (p *Process) consumeStderr(done chan bool) { reader := bufio.NewReader(p.stderr) for true { line, err := reader.ReadBytes('\n') if len(line) == 0 || err == io.EOF { done <- true return } var message consoleMessage if err := json.Unmarshal(line, &message); err != nil { os.Stderr.Write(line) } else { if message.Stderr != nil { os.Stderr.Write(message.Stderr) } if message.Stdout != nil { os.Stdout.Write(message.Stdout) } } } }
43
jsii-runtime-go
aws
Go
package process import ( "fmt" "regexp" "github.com/Masterminds/semver/v3" ) type handshakeResponse struct { Hello string `json:"hello"` } func (h *handshakeResponse) runtimeVersion() (*semver.Version, error) { re := regexp.MustCompile("@") parts := re.Split(h.Hello, 3) switch len(parts) { case 2: return semver.NewVersion(parts[1]) case 3: return semver.NewVersion(parts[2]) default: return nil, fmt.Errorf("invalid handshake payload: %v", h.Hello) } }
26
jsii-runtime-go
aws
Go
package process import ( "encoding/json" "errors" "fmt" "io" "io/ioutil" "os" "os/exec" "runtime" "strings" "sync" "github.com/Masterminds/semver/v3" "github.com/aws/jsii-runtime-go/internal/embedded" ) const JSII_NODE string = "JSII_NODE" const JSII_RUNTIME string = "JSII_RUNTIME" type ErrorResponse struct { Error string `json:"error"` Stack *string `json:"stack"` Name *string `json:"name"` } // Process is a simple interface over the child process hosting the // @jsii/kernel process. It only exposes a very straight-forward // request/response interface. type Process struct { compatibleVersions *semver.Constraints cmd *exec.Cmd tmpdir string stdin io.WriteCloser stdout io.ReadCloser stderr io.ReadCloser requests *json.Encoder responses *json.Decoder stderrDone chan bool started bool closed bool mutex sync.Mutex } // NewProcess prepares a new child process, but does not start it yet. It will // be automatically started whenever the client attempts to send a request // to it. // // If the JSII_RUNTIME environment variable is set, this command will be used // to start the child process, in a sub-shell (using %COMSPEC% or cmd.exe on // Windows; $SHELL or /bin/sh on other OS'es). Otherwise, the embedded runtime // application will be extracted into a temporary directory, and used. // // The current process' environment is inherited by the child process. Additional // environment may be injected into the child process' environment - all of which // with lower precedence than the launching process' environment, with the notable // exception of JSII_AGENT, which is reserved. func NewProcess(compatibleVersions string) (*Process, error) { p := Process{} if constraints, err := semver.NewConstraint(compatibleVersions); err != nil { return nil, err } else { p.compatibleVersions = constraints } if custom := os.Getenv(JSII_RUNTIME); custom != "" { var ( command string args []string ) // Sub-shelling in order to avoid having to parse arguments if runtime.GOOS == "windows" { // On windows, we use %ComSpec% if set, or cmd.exe if cmd := os.Getenv("ComSpec"); cmd != "" { command = cmd } else { command = "cmd.exe" } // The /d option disables Registry-defined AutoRun, it's safer to enable // The /s option tells cmd.exe the command is quoted as if it were typed into a prompt // The /c option tells cmd.exe to run the specified command and exit immediately args = []string{"/d", "/s", "/c", custom} } else { // On other OS'es, we use $SHELL and fall back to "/bin/sh" if shell := os.Getenv("SHELL"); shell != "" { command = shell } else { command = "/bin/sh" } args = []string{"-c", custom} } p.cmd = exec.Command(command, args...) } else if tmpdir, err := ioutil.TempDir("", "jsii-runtime.*"); err != nil { return nil, err } else { p.tmpdir = tmpdir if entrypoint, err := embedded.ExtractRuntime(tmpdir); err != nil { p.Close() return nil, err } else { if node := os.Getenv(JSII_NODE); node != "" { p.cmd = exec.Command(node, entrypoint) } else { p.cmd = exec.Command("node", entrypoint) } } } // Setting up environment - if duplicate keys are found, the last value is used, so we are careful with ordering. In // particular, we are setting NODE_OPTIONS only if `os.Environ()` does not have another value... So the user can // control the environment... However, JSII_AGENT must always be controlled by this process. p.cmd.Env = append([]string{"NODE_OPTIONS=--max-old-space-size=4069"}, os.Environ()...) p.cmd.Env = append(p.cmd.Env, fmt.Sprintf("JSII_AGENT=%v/%v/%v", runtime.Version(), runtime.GOOS, runtime.GOARCH)) if stdin, err := p.cmd.StdinPipe(); err != nil { p.Close() return nil, err } else { p.stdin = stdin p.requests = json.NewEncoder(stdin) } if stdout, err := p.cmd.StdoutPipe(); err != nil { p.Close() return nil, err } else { p.stdout = stdout p.responses = json.NewDecoder(stdout) } if stderr, err := p.cmd.StderrPipe(); err != nil { p.Close() return nil, err } else { p.stderr = stderr } return &p, nil } func (p *Process) ensureStarted() error { if p.closed { return fmt.Errorf("this process has been closed") } if p.started { return nil } if err := p.cmd.Start(); err != nil { p.Close() return err } p.started = true done := make(chan bool, 1) go p.consumeStderr(done) p.stderrDone = done var handshake handshakeResponse if err := p.readResponse(&handshake); err != nil { p.Close() return err } if runtimeVersion, err := handshake.runtimeVersion(); err != nil { p.Close() return err } else if ok, errs := p.compatibleVersions.Validate(runtimeVersion); !ok { causes := make([]string, len(errs)) for i, err := range errs { causes[i] = fmt.Sprintf("- %v", err) } p.Close() return fmt.Errorf("incompatible runtime version:\n%v", strings.Join(causes, "\n")) } go func() { err := p.cmd.Wait() if err != nil { fmt.Fprintf(os.Stderr, "Runtime process exited abnormally: %v", err.Error()) } p.Close() }() return nil } // Request starts the child process if that has not happened yet, then // encodes the supplied request and sends it to the child process // via the requests channel, then decodes the response into the provided // response pointer. If the process is not in a usable state, or if the // encoding fails, an error is returned. func (p *Process) Request(request interface{}, response interface{}) error { if err := p.ensureStarted(); err != nil { return err } if err := p.requests.Encode(request); err != nil { p.Close() return err } return p.readResponse(response) } func (p *Process) readResponse(into interface{}) error { if !p.responses.More() { return fmt.Errorf("no response received from child process") } var raw json.RawMessage var respmap map[string]interface{} err := p.responses.Decode(&raw) if err != nil { return err } err = json.Unmarshal(raw, &respmap) if err != nil { return err } var errResp ErrorResponse if _, ok := respmap["error"]; ok { json.Unmarshal(raw, &errResp) if errResp.Name != nil && *errResp.Name == "@jsii/kernel.Fault" { return fmt.Errorf("JsiiError: %s", *errResp.Name) } return errors.New(errResp.Error) } return json.Unmarshal(raw, &into) } func (p *Process) Close() { if p.closed { return } // Acquire the lock, so we don't try to concurrently close multiple times p.mutex.Lock() defer p.mutex.Unlock() // Check again now that we own the lock, it may be a fast exit! if p.closed { return } if p.stdin != nil { // Try to send the exit message, this might fail, but we can ignore that. p.stdin.Write([]byte("{\"exit\":0}\n")) // Close STDIN for the child process now. Ignoring errors, as it may // have been closed already (e.g: if the process exited). p.stdin.Close() p.stdin = nil } if p.stdout != nil { // Close STDOUT for the child process now, as we don't expect to receive // responses anymore. Ignoring errors, as it may have been closed // already (e.g: if the process exited). p.stdout.Close() p.stdout = nil } if p.stderrDone != nil { // Wait for the stderr sink goroutine to have finished <-p.stderrDone p.stderrDone = nil } if p.stderr != nil { // Close STDERR for the child process now, as we're no longer consuming // it anyway. Ignoring errors, as it may havebeen closed already (e.g: // if the process exited). p.stderr.Close() p.stderr = nil } if p.cmd != nil { // Wait for the child process to be dead and gone (should already be) p.cmd.Wait() p.cmd = nil } if p.tmpdir != "" { // Clean up any temporary directory we provisioned. if err := os.RemoveAll(p.tmpdir); err != nil { fmt.Fprintf(os.Stderr, "could not clean up temporary directory: %v\n", err) } p.tmpdir = "" } p.closed = true }
301
jsii-runtime-go
aws
Go
package process import ( _ "embed" "fmt" "io/ioutil" "os" "os/exec" "runtime" "strings" "testing" ) //go:embed jsii-mock-runtime.js var mockRuntimeSource []byte var mockRuntime string func TestMain(m *testing.M) { file, _ := ioutil.TempFile("", "jsii-mock-runtime.*.js") if _, err := file.Write(mockRuntimeSource); err != nil { panic(err) } file.Close() mockRuntime = file.Name() status := m.Run() // Clean up temporary file os.Remove(mockRuntime) os.Exit(status) } // TestVersionCheck ensures the version check logic works correctly. As a side // benefit, it validates we are correctly launching custom JSII_RUNTIME processes // as this relies on a mock implementation. func TestVersionCheck(t *testing.T) { acceptedVersions := []string{"4.3.2", "4.3.1337", "4.1337.42"} for _, mockVersion := range acceptedVersions { t.Run(fmt.Sprintf("accepts version %v", mockVersion), func(t *testing.T) { oldJsiiRuntime := os.Getenv(JSII_RUNTIME) if runtime, err := makeCustomRuntime(mockVersion); err != nil { t.Fatal(err) } else { os.Setenv(JSII_RUNTIME, runtime) } defer os.Setenv(JSII_RUNTIME, oldJsiiRuntime) process, err := NewProcess(fmt.Sprintf("^4.3.2")) if err != nil { t.Fatal(err) return } defer process.Close() t.Logf("Subprocess command: %v", strings.Join(process.cmd.Args, " ")) var ( request = EchoRequest{Message: "Oh, hi!"} response EchoResponse ) if err := process.Request(request, &response); err != nil { t.Fatal(err) } if response.Message != request.Message { t.Errorf("Expected %v, received %v", request.Message, response.Message) } }) } rejectedVersions := []string{"3.1337.42", "5.0.0-0", "4.3.2-pre.0", "4.3.3-pre.0"} for _, mockVersion := range rejectedVersions { t.Run(fmt.Sprintf("rejects version %v", mockVersion), func(t *testing.T) { oldJsiiRuntime := os.Getenv(JSII_RUNTIME) if runtime, err := makeCustomRuntime(mockVersion); err != nil { t.Fatal(err) } else { os.Setenv(JSII_RUNTIME, runtime) } defer os.Setenv(JSII_RUNTIME, oldJsiiRuntime) process, err := NewProcess("^4.3.2") if err != nil { t.Fatal(err) return } defer process.Close() t.Logf("Subprocess command: %v", strings.Join(process.cmd.Args, " ")) var ( request = EchoRequest{Message: "Oh, hi!"} response EchoResponse ) if err := process.Request(request, &response); err == nil { t.Errorf("expected an error, but no error received") } else if !strings.Contains(err.Error(), "incompatible runtime version") { t.Errorf("expected incompatible runtime version error, got %v", err.Error()) } }) } } func TestJSIINode(t *testing.T) { t.Run("successful node invocation", func(t *testing.T) { node, err := getNodePath() if err != nil { t.Fatal(err) return } oldJsiiNode := os.Getenv(JSII_NODE) os.Setenv(JSII_NODE, node) defer os.Setenv(JSII_NODE, oldJsiiNode) process, err := NewProcess("0.0.0") if err != nil { t.Fatal(err) return } defer process.Close() err = process.Request(TestRequest{"stats"}, &TestResponse{}) if err != nil { t.Fatal(err) return } }) t.Run("unsuccessful node invocation", func(t *testing.T) { oldJsiiNode := os.Getenv(JSII_NODE) os.Setenv(JSII_NODE, "./absolute-gibberish") defer os.Setenv(JSII_NODE, oldJsiiNode) process, err := NewProcess("0.0.0") if err != nil { t.Fatal(err) return } defer process.Close() if err := process.Request(TestRequest{"stats"}, &TestResponse{}); err == nil { t.Errorf("expected an error, but no error received") } else if !strings.Contains(err.Error(), "no such file or directory") && !strings.Contains(err.Error(), "file does not exist") { // We have 2 options here because Windows returns a different error message, of course... t.Errorf("expected 'no such file or directory' or 'file does not exist', got %v", err.Error()) } }) } type TestRequest struct { Api string `json:"api"` } type TestResponse struct { } type EchoRequest struct { Message string `json:"message"` } type EchoResponse struct { Message string `json:"message"` } func makeCustomRuntime(mockVersion string) (string, error) { node, err := getNodePath() if err != nil { return "", err } return fmt.Sprintf("%v %v %v", node, mockRuntime, mockVersion), nil } func getNodePath() (string, error) { var ( node string err error ) if runtime.GOOS == "windows" { node, err = exec.LookPath("node.exe") } else { node, err = exec.LookPath("node") } return node, err }
188
jsii-runtime-go
aws
Go
// Package objectstore implements support for tracking a mapping of object // references to and from their instance ID. It tracks objects by proxy of their // memory address (i.e: pointer value), in order to avoid the pitfalls of go's // standard object equality mechanism (which is also reflect.Value's equality // mechanism) causing distinct instances appearing to be equal (including when // used as keys to a map). package objectstore
8
jsii-runtime-go
aws
Go
package objectstore import ( "fmt" "reflect" "github.com/aws/jsii-runtime-go/internal/api" ) // stringSet is a set of strings, implemented as a map from string to an // arbitrary 0-width value. type stringSet map[string]struct{} // ObjectStore tracks object instances for which an identifier has been // associated. Object to instanceID association is tracked using the object // memory address (aka pointer value) in order to not have issues with go's // standard object equality rules (we need distinct - but possibly equal) object // instances to be considered as separate entities for our purposes. type ObjectStore struct { // objectToID associates an object's memory address (pointer value) with an // instanceID. This includes aliases (anonymous embedded values) of objects // passed to the Register method. objectToID map[uintptr]string // idToObject associates an instanceID with the first reflect.Value instance // that represents the top-level object that was registered with the // instanceID first via the Register method. idToObject map[string]reflect.Value // idToObjects associates an instanceID with the reflect.Value instances that // represent the top-level objects that were registered with the instanceID // via the Register method. idToObjects map[string]map[reflect.Value]struct{} // idToInterfaces associates an instanceID with the set of interfaces that it // is known to implement. // // Incorrect use of the UnsafeCast function may result in an instance's // interface list containing interfaces that it does not actually implement. idToInterfaces map[string]stringSet } // New initializes a new ObjectStore. func New() *ObjectStore { return &ObjectStore{ objectToID: make(map[uintptr]string), idToObject: make(map[string]reflect.Value), idToObjects: make(map[string]map[reflect.Value]struct{}), idToInterfaces: make(map[string]stringSet), } } // Register associates the provided value with the given instanceID. It also // registers any anonymously embedded value (transitively) against the same // instanceID, so that methods promoted from those resolve the correct // instanceID, too. // // Returns an error if the provided value is not a pointer value; if the value // or any of it's (transitively) anonymous embeds have already been registered // against a different instanceID; of if the provided instanceID was already // associated to a different value. // // The call is idempotent: calling Register again with the same value and // instanceID does not result in an error. func (o *ObjectStore) Register(value reflect.Value, objectRef api.ObjectRef) error { var err error if value, err = canonicalValue(value); err != nil { return err } ptr := value.Pointer() if existing, found := o.objectToID[ptr]; found { if existing == objectRef.InstanceID { o.mergeInterfaces(objectRef) return nil } return fmt.Errorf("attempting to register %v as %v, but it was already registered as %v", value, objectRef.InstanceID, existing) } aliases := findAliases(value) if existing, found := o.idToObjects[objectRef.InstanceID]; found { if _, found := existing[value]; found { o.mergeInterfaces(objectRef) return nil } // Value already exists (e.g: a constructor made a callback with "this" // passed as an argument). We make the current value(s) an alias of the new // one. for existing := range existing { aliases = append(aliases, existing) } } for _, alias := range aliases { ptr := alias.Pointer() if existing, found := o.objectToID[ptr]; found && existing != objectRef.InstanceID { return fmt.Errorf("value %v is embedded in %v which has ID %v, but was already assigned %v", alias.String(), value.String(), objectRef.InstanceID, existing) } } o.objectToID[ptr] = objectRef.InstanceID // Only add to idToObject if this is the first time this InstanceID is registered if _, found := o.idToObject[objectRef.InstanceID]; !found { o.idToObject[objectRef.InstanceID] = value } if _, found := o.idToObjects[objectRef.InstanceID]; !found { o.idToObjects[objectRef.InstanceID] = make(map[reflect.Value]struct{}) } o.idToObjects[objectRef.InstanceID][value] = struct{}{} for _, alias := range aliases { o.objectToID[alias.Pointer()] = objectRef.InstanceID } o.mergeInterfaces(objectRef) return nil } // mergeInterfaces adds all interfaces carried by the provided objectRef to the // tracking set for the objectRef's InstanceID. Does nothing if no interfaces // are designated on the objectRef. func (o *ObjectStore) mergeInterfaces(objectRef api.ObjectRef) { // If we don't have interfaces, we have nothing to do... if objectRef.Interfaces == nil { return } // Find or create the interface list for the relevant InstanceID var interfaces stringSet if list, found := o.idToInterfaces[objectRef.InstanceID]; found { interfaces = list } else { interfaces = make(stringSet) o.idToInterfaces[objectRef.InstanceID] = interfaces } // Add any missing interface to the list. for _, iface := range objectRef.Interfaces { interfaces[string(iface)] = struct{}{} } } // InstanceID attempts to determine the instanceID associated with the provided // value, if any. Returns the existing instanceID and a boolean informing // whether an instanceID was already found or not. // // The InstanceID method is safe to call with values that are not track-able in // an ObjectStore (i.e: non-pointer values, primitive values, etc...). func (o *ObjectStore) InstanceID(value reflect.Value) (instanceID string, found bool) { var err error if value, err = canonicalValue(value); err == nil { ptr := value.Pointer() instanceID, found = o.objectToID[ptr] } return } // Interfaces returns the set of interfaces associated with the provided // instanceID. // // It returns a nil slice in case the instancceID is invalid, or if it does not // have any associated interfaces. func (o *ObjectStore) Interfaces(instanceID string) []api.FQN { if set, found := o.idToInterfaces[instanceID]; found { interfaces := make([]api.FQN, 0, len(set)) for iface := range set { interfaces = append(interfaces, api.FQN(iface)) } return interfaces } else { return nil } } // GetObject attempts to retrieve the object value associated with the given // instanceID. Returns the existing value and a boolean informing whether a // value was associated with this instanceID or not. // // The GetObject method is safe to call with an instanceID that was never // registered with the ObjectStore. func (o *ObjectStore) GetObject(instanceID string) (value reflect.Value, found bool) { value, found = o.idToObject[instanceID] return } // GetObjectAs attempts to retrieve the object value associated with the given // instanceID, compatible with the given type. Returns the existing value and a // boolean informing whether a value was associated with this instanceID and // compatible with this type or not. // // The GetObjectAs method is safe to call with an instanceID that was never // registered with the ObjectStore. func (o *ObjectStore) GetObjectAs(instanceID string, typ reflect.Type) (value reflect.Value, found bool) { found = false if values, exists := o.idToObjects[instanceID]; exists { for value = range values { if value.Type().AssignableTo(typ) { value = value.Convert(typ) found = true return } } } return } // canonicalValue ensures the same reference is always considered for object // identity (especially in maps), so that we don't get surprised by pointer to // struct versus struct value versus opaque interface value, etc... func canonicalValue(value reflect.Value) (reflect.Value, error) { if value.Kind() == reflect.Ptr && value.Elem().Kind() == reflect.Struct { return value, nil } // If this is a pointer to something, de-references it. result := reflect.ValueOf(reflect.Indirect(value).Interface()) if result.Kind() != reflect.Ptr { return reflect.Value{}, fmt.Errorf("illegal argument: %v is not a pointer", result.String()) } return result, nil } // findAliases traverses the provided object value to recursively identify all // anonymous embedded values, which will then be registered against the same // instanceID as the embedding value. // // This function assumes the provided value is either a reflect.Struct or a // pointer to a reflect.Struct (possibly as a reflect.Interface). Calling with // a nil value, or a value that is not ultimately a reflect.Struct may result // in panic. func findAliases(value reflect.Value) []reflect.Value { var result []reflect.Value // Indirect so we always work on the pointer referree value = reflect.Indirect(value) t := value.Type() numField := t.NumField() for i := 0; i < numField; i++ { f := t.Field(i) // Ignore non-anonymous fields (including padding) if !f.Anonymous { continue } fv := value.FieldByIndex(f.Index) if fv.Kind() == reflect.Interface { // If an interface, de-reference to get to the struct type. fv = reflect.ValueOf(fv.Interface()) } if fv.Kind() == reflect.Struct { // If a struct, get the address of the member. fv = fv.Addr() } result = append(result, fv) // Recurse down to collect nested aliases result = append(result, findAliases(fv)...) } return result }
266
jsii-runtime-go
aws
Go
package typeregistry import ( "reflect" "strings" "github.com/aws/jsii-runtime-go/internal/api" ) // DiscoverImplementation determines the list of registered interfaces that are // implemented by the provided type, and returns the list of their FQNs and // overrides for all their combined methods and properties. func (t *TypeRegistry) DiscoverImplementation(vt reflect.Type) (interfaces []api.FQN, overrides []api.Override) { if strings.HasPrefix(vt.Name(), "jsiiProxy_") { return } registeredOverrides := make(map[string]bool) embeds := t.registeredBasesOf(vt) pt := reflect.PtrTo(vt) OuterLoop: for fqn, members := range t.typeMembers { iface := t.fqnToType[fqn] if iface.Kind == classType || !(vt.AssignableTo(iface.Type) || pt.AssignableTo(iface.Type)) { continue } for _, embed := range embeds { if embed.AssignableTo(iface.Type) { continue OuterLoop } } // Found a hit, registering it's FQN in the list! interfaces = append(interfaces, fqn) // Now, collecting all members thereof for _, override := range members { if identifier := override.GoName(); !registeredOverrides[identifier] { registeredOverrides[identifier] = true overrides = append(overrides, override) } } } return } // registeredBasesOf looks for known base type anonymously embedded (not // recursively) in the given value type. Interfaces implemented by those types // are actually not "additional interfaces" (they are implied). func (t *TypeRegistry) registeredBasesOf(vt reflect.Type) []reflect.Type { if vt.Kind() == reflect.Ptr { vt = vt.Elem() } if vt.Kind() != reflect.Struct { return nil } n := vt.NumField() result := make([]reflect.Type, 0, n) for i := 0; i < n; i++ { f := vt.Field(i) if !f.Anonymous { continue } if _, ok := t.proxyMakers[f.Type]; ok { result = append(result, f.Type) } } return result }
72
jsii-runtime-go
aws
Go
// Package typeregistry offers features useful to manage the registration and // operation of types in the context of the jsii runtime. These are used to // support type conversion for values exchanged between the child node process // and the go application. package typeregistry
6
jsii-runtime-go
aws
Go
package typeregistry import ( "github.com/aws/jsii-runtime-go/internal/api" ) func (t *TypeRegistry) GetOverride(fqn api.FQN, n string) (api.Override, bool) { if members, ok := t.typeMembers[fqn]; ok { for _, member := range members { if member.GoName() == n { return member, true } } } return nil, false }
18
jsii-runtime-go
aws
Go
package typeregistry import ( "fmt" "reflect" "github.com/aws/jsii-runtime-go/internal/api" ) type typeKind uint8 const ( _ = iota classType typeKind = iota enumType typeKind = iota interfaceType typeKind = iota structType typeKind = iota ) type registeredType struct { Type reflect.Type Kind typeKind } type registeredStruct struct { FQN api.FQN Fields []reflect.StructField Validator func(interface{}, func() string) error } // RegisterClass maps the given FQN to the provided class interface, list of // overrides, and proxy maker function. This returns an error if the class // type is not a go interface. func (t *TypeRegistry) RegisterClass(fqn api.FQN, class reflect.Type, overrides []api.Override, maker func() interface{}) error { if class.Kind() != reflect.Interface { return fmt.Errorf("the provided class is not an interface: %v", class) } if existing, exists := t.fqnToType[fqn]; exists && existing.Type != class { return fmt.Errorf("another type was already registered with %v: %v", fqn, existing) } t.fqnToType[fqn] = registeredType{class, classType} t.proxyMakers[class] = maker // Skipping registration if there are no members, as this would have no use. if len(overrides) > 0 { t.typeMembers[fqn] = make([]api.Override, len(overrides)) copy(t.typeMembers[fqn], overrides) } return nil } // RegisterEnum maps the given FQN to the provided enum type, and records the // provided members map (jsii member name => go value). This returns an error // if the provided enum is not a string derivative, or of any of the provided // member values has a type other than enm. func (t *TypeRegistry) RegisterEnum(fqn api.FQN, enm reflect.Type, members map[string]interface{}) error { if enm.Kind() != reflect.String { return fmt.Errorf("the provided enum is not a string derivative: %v", enm) } if existing, exists := t.fqnToType[fqn]; exists && existing.Type != enm { return fmt.Errorf("another type was already registered with %v: %v", fqn, existing) } if existing, exists := t.typeToEnumFQN[enm]; exists && existing != fqn { return fmt.Errorf("attempted to re-register %v as %v, but it was registered as %v", enm, fqn, existing) } for memberName, memberVal := range members { vt := reflect.ValueOf(memberVal).Type() if vt != enm { return fmt.Errorf("the enum entry for key %v has incorrect type %v", memberName, vt) } // Not setting in t.fqnToEnumMember here so we don't cause any side-effects // if the pre-condition fails at any point. This is done in a second loop. } t.fqnToType[fqn] = registeredType{enm, enumType} t.typeToEnumFQN[enm] = fqn for memberName, memberVal := range members { memberFQN := fmt.Sprintf("%v/%v", fqn, memberName) t.fqnToEnumMember[memberFQN] = memberVal } return nil } // RegisterInterface maps the given FQN to the provided interface type, list of // overrides, and proxy maker function. Returns an error if the provided interface // is not a go interface. func (t *TypeRegistry) RegisterInterface(fqn api.FQN, iface reflect.Type, overrides []api.Override, maker func() interface{}) error { if iface.Kind() != reflect.Interface { return fmt.Errorf("the provided interface is not an interface: %v", iface) } if existing, exists := t.fqnToType[fqn]; exists && existing.Type != iface { return fmt.Errorf("another type was already registered with %v: %v", fqn, existing) } if existing, exists := t.typeToInterfaceFQN[iface]; exists && existing != fqn { return fmt.Errorf("anoter FQN was already registered with %v: %v", iface, existing) } t.fqnToType[fqn] = registeredType{iface, interfaceType} t.typeToInterfaceFQN[iface] = fqn t.proxyMakers[iface] = maker // Skipping registration if there are no members, as this would have no use. if len(overrides) > 0 { t.typeMembers[fqn] = make([]api.Override, len(overrides)) copy(t.typeMembers[fqn], overrides) } return nil } // RegisterStruct maps the given FQN to the provided struct type, and struct // interface. Returns an error if the provided struct type is not a go struct, // or the provided iface not a go interface. func (t *TypeRegistry) RegisterStruct(fqn api.FQN, strct reflect.Type) error { if strct.Kind() != reflect.Struct { return fmt.Errorf("the provided struct is not a struct: %v", strct) } if existing, exists := t.fqnToType[fqn]; exists && existing.Type != strct { return fmt.Errorf("another type was already registered with %v: %v", fqn, existing) } if existing, exists := t.structInfo[strct]; exists && existing.FQN != fqn { return fmt.Errorf("attempting to register type %v as %v, but it was already registered as: %v", strct, fqn, existing.FQN) } numField := strct.NumField() fields := make([]reflect.StructField, 0, numField) for i := 0; i < numField; i++ { field := strct.Field(i) if field.Anonymous { return fmt.Errorf("unexpected anonymous field %v in struct %v (%v)", field, fqn, strct) } if field.PkgPath != "" { return fmt.Errorf("unexpected un-exported field %v in struct %v (%v)", field, fqn, strct) } if field.Tag.Get("json") == "" { return fmt.Errorf("missing json tag on struct field %v of %v (%v)", field, fqn, strct) } fields = append(fields, field) } t.fqnToType[fqn] = registeredType{strct, structType} t.structInfo[strct] = registeredStruct{FQN: fqn, Fields: fields} return nil } // RegisterStructValidator adds a validator function to an already registered struct type. This is separate call largely // to maintain backwards compatibility with existing code. func (t *TypeRegistry) RegisterStructValidator(strct reflect.Type, validator func(interface{}, func() string) error) error { if strct.Kind() != reflect.Struct { return fmt.Errorf("the provided struct is not a struct: %v", strct) } info, ok := t.structInfo[strct] if !ok { return fmt.Errorf("the provided struct %v is not registered (call RegisterStruct first)", strct) } info.Validator = validator t.structInfo[strct] = info return nil }
171
jsii-runtime-go
aws
Go
package typeregistry import ( "fmt" "reflect" "github.com/aws/jsii-runtime-go/internal/api" ) // TypeRegistry is used to record runtime type information about the loaded // modules, which is later used to correctly convert objects received from the // JavaScript process into native go values. type TypeRegistry struct { // fqnToType is used to obtain the native go type for a given jsii fully // qualified type name. The kind of type being returned depends on what the // FQN represents... This will be the second argument of provided to a // register* function. // enums are not included fqnToType map[api.FQN]registeredType // fqnToEnumMember maps enum member FQNs (e.g. "jsii-calc.StringEnum/A") to // the corresponding go const for this member. fqnToEnumMember map[string]interface{} // typeToEnumFQN maps Go enum type ("StringEnum") to the corresponding jsii // enum FQN (e.g. "jsii-calc.StringEnum") typeToEnumFQN map[reflect.Type]api.FQN // typeToInterfaceFQN maps Go interface type ("SomeInterface") to the // corresponding jsii interface FQN (e.g: "jsii-calc.SomeInterface") typeToInterfaceFQN map[reflect.Type]api.FQN // structInfo maps registered struct types to all their fields, and possibly a validator structInfo map[reflect.Type]registeredStruct // proxyMakers map registered interface types to a proxy maker function. proxyMakers map[reflect.Type]func() interface{} // typeMembers maps each class or interface FQN to the set of members it // implements in the form of api.Override values. typeMembers map[api.FQN][]api.Override } type anonymousProxy struct{ _ int } // Padded so it's not 0-sized // New creates a new type registry. func New() *TypeRegistry { registry := TypeRegistry{ fqnToType: make(map[api.FQN]registeredType), fqnToEnumMember: make(map[string]interface{}), typeToEnumFQN: make(map[reflect.Type]api.FQN), typeToInterfaceFQN: make(map[reflect.Type]api.FQN), structInfo: make(map[reflect.Type]registeredStruct), proxyMakers: make(map[reflect.Type]func() interface{}), typeMembers: make(map[api.FQN][]api.Override), } // Ensure we can initialize proxies for `interface{}` when a method returns `any`. registry.proxyMakers[reflect.TypeOf((*interface{})(nil)).Elem()] = func() interface{} { return &anonymousProxy{} } return &registry } // IsAnonymousProxy tells whether the value v is an anonymous object proxy, or // a pointer to one. func (t *TypeRegistry) IsAnonymousProxy(v interface{}) bool { _, ok := v.(*anonymousProxy) if !ok { _, ok = v.(anonymousProxy) } return ok } // StructFields returns the list of fields associated with a jsii struct type, // the jsii fully qualified type name, and a boolean telling whether the // provided type was a registered jsii struct type. func (t *TypeRegistry) StructFields(typ reflect.Type) (fields []reflect.StructField, fqn api.FQN, ok bool) { var info registeredStruct if info, ok = t.structInfo[typ]; !ok { return } fqn = info.FQN fields = make([]reflect.StructField, len(info.Fields)) copy(fields, info.Fields) return } // FindType returns the registered type corresponding to the provided jsii FQN. func (t *TypeRegistry) FindType(fqn api.FQN) (typ reflect.Type, ok bool) { var reg registeredType if reg, ok = t.fqnToType[fqn]; ok { typ = reg.Type } return } // InitJsiiProxy initializes a jsii proxy value at the provided pointer. It // returns an error if the pointer does not have a value of a registered // proxyable type (that is, a class or interface type). func (t *TypeRegistry) InitJsiiProxy(val reflect.Value, valType reflect.Type) error { switch valType.Kind() { case reflect.Interface: if maker, ok := t.proxyMakers[valType]; ok { made := maker() val.Set(reflect.ValueOf(made)) return nil } return fmt.Errorf("unable to make an instance of unregistered interface %v", valType) case reflect.Struct: if !val.IsZero() { return fmt.Errorf("refusing to initialize non-zero-value struct %v", val) } numField := valType.NumField() for i := 0; i < numField; i++ { field := valType.Field(i) if field.Name == "_" { // Ignore any padding continue } if !field.Anonymous { return fmt.Errorf("refusing to initialize non-anonymous field %v of %v", field.Name, val) } if err := t.InitJsiiProxy(val.Field(i), field.Type); err != nil { return err } } return nil default: return fmt.Errorf("unable to make an instance of %v (neither a struct nor interface)", valType) } } // EnumMemberForEnumRef returns the go enum member corresponding to a jsii fully // qualified enum member name (e.g: "jsii-calc.StringEnum/A"). If no enum member // was registered (via registerEnum) for the provided enumref, an error is // returned. func (t *TypeRegistry) EnumMemberForEnumRef(ref api.EnumRef) (interface{}, error) { if member, ok := t.fqnToEnumMember[ref.MemberFQN]; ok { return member, nil } return nil, fmt.Errorf("no enum member registered for %v", ref.MemberFQN) } // TryRenderEnumRef returns an enumref if the provided value corresponds to a // registered enum type. The returned enumref is nil if the provided enum value // is a zero-value (i.e: ""). func (t *TypeRegistry) TryRenderEnumRef(value reflect.Value) (ref *api.EnumRef, isEnumRef bool) { if value.Kind() != reflect.String { isEnumRef = false return } if enumFQN, ok := t.typeToEnumFQN[value.Type()]; ok { isEnumRef = true if memberName := value.String(); memberName != "" { ref = &api.EnumRef{MemberFQN: fmt.Sprintf("%v/%v", enumFQN, memberName)} } else { ref = nil } } else { isEnumRef = false } return } func (t *TypeRegistry) InterfaceFQN(typ reflect.Type) (fqn api.FQN, found bool) { fqn, found = t.typeToInterfaceFQN[typ] return }
176
jsii-runtime-go
aws
Go
package typeregistry import ( "fmt" "reflect" ) // ValidateStruct runs validations on the supplied struct to determine whether // it is valid. In particular, it checks union-typed properties to ensure the // provided value is of one of the allowed types. // // May panic if v is not a pointer to a struct value. func (t *TypeRegistry) ValidateStruct(v interface{}, d func() string) error { rt := reflect.TypeOf(v).Elem() info, ok := t.structInfo[rt] if !ok { return fmt.Errorf("%v: %v is not a know struct type", d(), rt) } // There may not be a validator (type is simple enough, etc...). if info.Validator != nil { return info.Validator(v, d) } return nil }
28
jsii-runtime-go
aws
Go
// Package runtime provides the APIs used by code generated by the `jsii-pacmak` // tool to interact with the `@jsii/kernel` process. It is not intended for // users to directly interact with, and doing so could result in incorrect // behavior. package runtime
6
jsii-runtime-go
aws
Go
package runtime import ( "reflect" "sort" "testing" ) type IFace interface { M1() M2() M3() } type Base struct { X, Y int } func (b *Base) M1() {} func (b *Base) M2() {} func (b *Base) M3() {} type D1 struct { *Base } func (d *D1) M1() {} func (d *D1) X1() {} type D2 struct { Name string IFace } func (d *D2) M2() {} func (d *D2) X2() {} func TestOverrideReflection(t *testing.T) { testCases := [...]struct { //overriding instance val interface{} //instance overriding methods methods []string }{ {&Base{}, []string(nil)}, {&D1{&Base{}}, []string{"M1", "X1"}}, {&D2{Name: "abc", IFace: &D1{&Base{}}}, []string{"M1", "X1", "M2", "X2"}}, } for _, tc := range testCases { sort.Slice(tc.methods, func(i, j int) bool { return tc.methods[i] < tc.methods[j] }) } for _, tc := range testCases { methods := getMethodOverrides(tc.val, "Base") sort.Slice(methods, func(i, j int) bool { return methods[i] < methods[j] }) if !reflect.DeepEqual(methods, tc.methods) { t.Errorf("expect: %v, got: %v", tc.methods, methods) } } }
66
jsii-runtime-go
aws
Go
package runtime import ( "fmt" "reflect" "strings" "github.com/aws/jsii-runtime-go/internal/api" "github.com/aws/jsii-runtime-go/internal/kernel" ) // FQN represents a fully-qualified type name in the jsii type system. type FQN api.FQN // Member is a runtime descriptor for a class or interface member type Member interface { toOverride() api.Override } // MemberMethod is a runtime descriptor for a class method (implementation of Member) type MemberMethod api.MethodOverride func (m MemberMethod) toOverride() api.Override { return api.MethodOverride(m) } // MemberProperty is a runtime descriptor for a class or interface property (implementation of Member) type MemberProperty api.PropertyOverride func (m MemberProperty) toOverride() api.Override { return api.PropertyOverride(m) } // Load ensures a npm package is loaded in the jsii kernel. func Load(name string, version string, tarball []byte) { c := kernel.GetClient() _, err := c.Load(kernel.LoadProps{ Name: name, Version: version, }, tarball) if err != nil { panic(err) } } // RegisterClass associates a class fully qualified name to the specified class // interface, member list, and proxy maker function. Panics if class is not a go // interface, or if the provided fqn was already used to register a different type. func RegisterClass(fqn FQN, class reflect.Type, members []Member, maker func() interface{}) { client := kernel.GetClient() overrides := make([]api.Override, len(members)) for i, m := range members { overrides[i] = m.toOverride() } if err := client.Types().RegisterClass(api.FQN(fqn), class, overrides, maker); err != nil { panic(err) } } // RegisterEnum associates an enum's fully qualified name to the specified enum // type, and members. Panics if enum is not a reflect.String type, any value in // the provided members map is of a type other than enum, or if the provided // fqn was already used to register a different type. func RegisterEnum(fqn FQN, enum reflect.Type, members map[string]interface{}) { client := kernel.GetClient() if err := client.Types().RegisterEnum(api.FQN(fqn), enum, members); err != nil { panic(err) } } // RegisterInterface associates an interface's fully qualified name to the // specified interface type, member list, and proxy maker function. Panics if iface is not // an interface, or if the provided fqn was already used to register a different type. func RegisterInterface(fqn FQN, iface reflect.Type, members []Member, maker func() interface{}) { client := kernel.GetClient() overrides := make([]api.Override, len(members)) for i, m := range members { overrides[i] = m.toOverride() } if err := client.Types().RegisterInterface(api.FQN(fqn), iface, overrides, maker); err != nil { panic(err) } } // RegisterStruct associates a struct's fully qualified name to the specified // struct type. Panics if strct is not a struct, or if the provided fqn was // already used to register a different type. func RegisterStruct(fqn FQN, strct reflect.Type) { client := kernel.GetClient() if err := client.Types().RegisterStruct(api.FQN(fqn), strct); err != nil { panic(err) } } // RegisterStructValidator adds a validator function to an already registered // struct type. This is separate call largely to maintain backwards compatibility // with existing code. func RegisterStructValidator(strct reflect.Type, validator func(interface{}, func() string) error) { client := kernel.GetClient() if err := client.Types().RegisterStructValidator(strct, validator); err != nil { panic(err) } } // InitJsiiProxy initializes a jsii proxy instance at the provided pointer. // Panics if the pointer cannot be initialized to a proxy instance (i.e: the // element of it is not a registered jsii interface or class type). func InitJsiiProxy(ptr interface{}) { ptrVal := reflect.ValueOf(ptr).Elem() if err := kernel.GetClient().Types().InitJsiiProxy(ptrVal, ptrVal.Type()); err != nil { panic(err) } } // IsAnonymousProxy tells whether the value v is an anonymous object proxy, or // a pointer to one. func IsAnonymousProxy(v interface{}) bool { return kernel.GetClient().Types().IsAnonymousProxy(v) } // Create will construct a new JSII object within the kernel runtime. This is // called by jsii object constructors. func Create(fqn FQN, args []interface{}, inst interface{}) { client := kernel.GetClient() instVal := reflect.ValueOf(inst) structVal := instVal.Elem() instType := structVal.Type() numField := instType.NumField() for i := 0; i < numField; i++ { field := instType.Field(i) if !field.Anonymous { continue } switch field.Type.Kind() { case reflect.Interface: fieldVal := structVal.Field(i) if !fieldVal.IsNil() { continue } if err := client.Types().InitJsiiProxy(fieldVal, fieldVal.Type()); err != nil { panic(err) } case reflect.Struct: fieldVal := structVal.Field(i) if !fieldVal.IsZero() { continue } if err := client.Types().InitJsiiProxy(fieldVal, fieldVal.Type()); err != nil { panic(err) } } } // Find method overrides thru reflection mOverrides := getMethodOverrides(inst, "jsiiProxy_") // If overriding struct has no overriding methods, could happen if // overriding methods are not defined with pointer receiver. if len(mOverrides) == 0 && !strings.HasPrefix(instType.Name(), "jsiiProxy_") { panic(fmt.Errorf("%v has no overriding methods. Overriding methods must be defined with a pointer receiver", instType.Name())) } var overrides []api.Override registry := client.Types() added := make(map[string]bool) for _, name := range mOverrides { // Use getter's name even if setter is overriden if strings.HasPrefix(name, "Set") { propName := name[3:] if override, ok := registry.GetOverride(api.FQN(fqn), propName); ok { if !added[propName] { added[propName] = true overrides = append(overrides, override) } continue } } if override, ok := registry.GetOverride(api.FQN(fqn), name); ok { if !added[name] { added[name] = true overrides = append(overrides, override) } } } interfaces, newOverrides := client.Types().DiscoverImplementation(instType) overrides = append(overrides, newOverrides...) res, err := client.Create(kernel.CreateProps{ FQN: api.FQN(fqn), Arguments: convertArguments(args), Interfaces: interfaces, Overrides: overrides, }) if err != nil { panic(err) } if err = client.RegisterInstance(instVal, api.ObjectRef{InstanceID: res.InstanceID, Interfaces: interfaces}); err != nil { panic(err) } } // Invoke will call a method on a jsii class instance. The response will be // decoded into the expected return type for the method being called. func Invoke(obj interface{}, method string, args []interface{}, ret interface{}) { client := kernel.GetClient() // Find reference to class instance in client ref, found := client.FindObjectRef(reflect.ValueOf(obj)) if !found { panic("No Object Found") } res, err := client.Invoke(kernel.InvokeProps{ Method: method, Arguments: convertArguments(args), ObjRef: ref, }) if err != nil { panic(err) } client.CastAndSetToPtr(ret, res.Result) } // InvokeVoid will call a void method on a jsii class instance. func InvokeVoid(obj interface{}, method string, args []interface{}) { client := kernel.GetClient() // Find reference to class instance in client ref, found := client.FindObjectRef(reflect.ValueOf(obj)) if !found { panic("No Object Found") } _, err := client.Invoke(kernel.InvokeProps{ Method: method, Arguments: convertArguments(args), ObjRef: ref, }) if err != nil { panic(err) } } // StaticInvoke will call a static method on a given jsii class. The response // will be decoded into the expected return type for the method being called. func StaticInvoke(fqn FQN, method string, args []interface{}, ret interface{}) { client := kernel.GetClient() res, err := client.SInvoke(kernel.StaticInvokeProps{ FQN: api.FQN(fqn), Method: method, Arguments: convertArguments(args), }) if err != nil { panic(err) } client.CastAndSetToPtr(ret, res.Result) } // StaticInvokeVoid will call a static void method on a given jsii class. func StaticInvokeVoid(fqn FQN, method string, args []interface{}) { client := kernel.GetClient() _, err := client.SInvoke(kernel.StaticInvokeProps{ FQN: api.FQN(fqn), Method: method, Arguments: convertArguments(args), }) if err != nil { panic(err) } } // Get reads a property value on a given jsii class instance. The response // should be decoded into the expected type of the property being read. func Get(obj interface{}, property string, ret interface{}) { client := kernel.GetClient() // Find reference to class instance in client ref, found := client.FindObjectRef(reflect.ValueOf(obj)) if !found { panic(fmt.Errorf("no object reference found for %v", obj)) } res, err := client.Get(kernel.GetProps{ Property: property, ObjRef: ref, }) if err != nil { panic(err) } client.CastAndSetToPtr(ret, res.Value) } // StaticGet reads a static property value on a given jsii class. The response // should be decoded into the expected type of the property being read. func StaticGet(fqn FQN, property string, ret interface{}) { client := kernel.GetClient() res, err := client.SGet(kernel.StaticGetProps{ FQN: api.FQN(fqn), Property: property, }) if err != nil { panic(err) } client.CastAndSetToPtr(ret, res.Value) } // Set writes a property on a given jsii class instance. The value should match // the type of the property being written, or the jsii kernel will crash. func Set(obj interface{}, property string, value interface{}) { client := kernel.GetClient() // Find reference to class instance in client ref, found := client.FindObjectRef(reflect.ValueOf(obj)) if !found { panic("No Object Found") } _, err := client.Set(kernel.SetProps{ Property: property, Value: client.CastPtrToRef(reflect.ValueOf(value)), ObjRef: ref, }) if err != nil { panic(err) } } // StaticSet writes a static property on a given jsii class. The value should // match the type of the property being written, or the jsii kernel will crash. func StaticSet(fqn FQN, property string, value interface{}) { client := kernel.GetClient() _, err := client.SSet(kernel.StaticSetProps{ FQN: api.FQN(fqn), Property: property, Value: client.CastPtrToRef(reflect.ValueOf(value)), }) if err != nil { panic(err) } } // convertArguments turns an argument struct and produces a list of values // ready for inclusion in an invoke or create request. func convertArguments(args []interface{}) []interface{} { if len(args) == 0 { return nil } result := make([]interface{}, len(args)) client := kernel.GetClient() for i, arg := range args { val := reflect.ValueOf(arg) result[i] = client.CastPtrToRef(val) } return result } // Get ptr's methods names which override "base" struct methods. // The "base" struct is identified by name prefix "basePrefix". func getMethodOverrides(ptr interface{}, basePrefix string) (methods []string) { // Methods override cache: [methodName]bool mCache := make(map[string]bool) getMethodOverridesRec(ptr, basePrefix, mCache) // Return overriden methods names in embedding hierarchy for m := range mCache { methods = append(methods, m) } return } func getMethodOverridesRec(ptr interface{}, basePrefix string, cache map[string]bool) { ptrType := reflect.TypeOf(ptr) if ptrType.Kind() != reflect.Ptr { return } structType := ptrType.Elem() if structType.Kind() != reflect.Struct { return } if strings.HasPrefix(structType.Name(), basePrefix) { // Skip base class return } ptrVal := reflect.ValueOf(ptr) structVal := ptrVal.Elem() // Add embedded/super overrides first for i := 0; i < structType.NumField(); i++ { field := structType.Field(i) if !field.Anonymous { continue } if field.Type.Kind() == reflect.Ptr || field.Type.Kind() == reflect.Interface { p := structVal.Field(i) if !p.IsNil() { getMethodOverridesRec(p.Interface(), basePrefix, cache) } } } // Add overrides in current struct // Current struct's value-type method-set valMethods := make(map[string]bool) for i := 0; i < structType.NumMethod(); i++ { valMethods[structType.Method(i).Name] = true } // Compare current struct's pointer-type method-set to its value-type method-set for i := 0; i < ptrType.NumMethod(); i++ { mn := ptrType.Method(i).Name if !valMethods[mn] { cache[mn] = true } } }
445
jsii-runtime-go
aws
Go
package runtime import "github.com/aws/jsii-runtime-go/internal/kernel" // ValidateStruct runs validations on the supplied struct to determine whether // it is valid. In particular, it checks union-typed properties to ensure the // provided value is of one of the allowed types. func ValidateStruct(v interface{}, d func() string) error { client := kernel.GetClient() return client.Types().ValidateStruct(v, d) }
12
karpenter
aws
Go
/* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package main import ( "github.com/samber/lo" "github.com/aws/karpenter/pkg/cloudprovider" "github.com/aws/karpenter/pkg/controllers" "github.com/aws/karpenter/pkg/operator" "github.com/aws/karpenter/pkg/webhooks" "github.com/aws/karpenter-core/pkg/cloudprovider/metrics" corecontrollers "github.com/aws/karpenter-core/pkg/controllers" "github.com/aws/karpenter-core/pkg/controllers/state" coreoperator "github.com/aws/karpenter-core/pkg/operator" corewebhooks "github.com/aws/karpenter-core/pkg/webhooks" ) func main() { ctx, op := operator.NewOperator(coreoperator.NewOperator()) awsCloudProvider := cloudprovider.New( op.InstanceTypesProvider, op.InstanceProvider, op.GetClient(), op.AMIProvider, op.SecurityGroupProvider, op.SubnetProvider, ) lo.Must0(op.AddHealthzCheck("cloud-provider", awsCloudProvider.LivenessProbe)) cloudProvider := metrics.Decorate(awsCloudProvider) op. WithControllers(ctx, corecontrollers.NewControllers( ctx, op.Clock, op.GetClient(), op.KubernetesInterface, state.NewCluster(op.Clock, op.GetClient(), cloudProvider), op.EventRecorder, cloudProvider, )...). WithWebhooks(corewebhooks.NewWebhooks()...). WithControllers(ctx, controllers.NewControllers( ctx, op.Session, op.Clock, op.GetClient(), op.EventRecorder, op.UnavailableOfferingsCache, awsCloudProvider, op.SubnetProvider, op.SecurityGroupProvider, op.PricingProvider, op.AMIProvider, )...). WithWebhooks(webhooks.NewWebhooks()...). Start(ctx) }
72
karpenter
aws
Go
/* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package main import ( "flag" "fmt" "go/format" "log" "net/http" "os" "sort" "strconv" "strings" "github.com/PuerkitoBio/goquery" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/ec2" "github.com/samber/lo" ) var uriSelectors = map[string]string{ "https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/general-purpose-instances.html": "#general-purpose-network-performance", "https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/compute-optimized-instances.html": "#compute-network-performance", "https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/memory-optimized-instances.html": "#memory-network-perf", "https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/storage-optimized-instances.html": "#storage-network-performance", "https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/accelerated-computing-instances.html": "#gpu-network-performance", } const fileFormat = ` %s package instancetype // GENERATED FILE. DO NOT EDIT DIRECTLY. // Update hack/code/bandwidth_gen.go and re-generate to edit // You can add instance types by adding to the --instance-types CLI flag var ( InstanceTypeBandwidthMegabits = map[string]int64{ %s } ) ` func main() { flag.Parse() if flag.NArg() != 1 { log.Fatalf("Usage: `bandwidth_gen.go pkg/providers/instancetype/zz_generated.bandwidth.go`") } bandwidth := map[string]int64{} for uri, selector := range uriSelectors { func() { response := lo.Must(http.Get(uri)) defer response.Body.Close() doc := lo.Must(goquery.NewDocumentFromReader(response.Body)) // grab two tables that contain the network performance values // first table will contain all the instance type and bandwidth data // some rows will will have vague describe such as "Very Low", "Low", "Low to Moderate", etc. // These instance types will can be found on the second table with absolute values in Gbps // If the instance type is skipped on the first table it will be grabbed on the second table for _, row := range doc.Find(selector).NextAllFiltered(".table-container").Eq(0).Find("tbody").Find("tr").Nodes { instanceTypeData := row.FirstChild.NextSibling.FirstChild.FirstChild.Data bandwidthData := row.FirstChild.NextSibling.NextSibling.NextSibling.FirstChild.Data // exclude all rows that contain any of the following strings if containsAny(bandwidthData, "Low", "Moderate", "High", "Up to") { continue } bandwidthSlice := strings.Split(bandwidthData, " ") // if the first value contains a multiplier i.e. (4x 100 Gigabit) if strings.HasSuffix(bandwidthSlice[0], "x") { multiplier := lo.Must(strconv.ParseFloat(bandwidthSlice[0][:len(bandwidthSlice[0])-1], 64)) bandwidth[instanceTypeData] = int64(lo.Must(strconv.ParseFloat(bandwidthSlice[1], 64)) * 1000 * multiplier) // Check row for instancetype for described network performance value i.e (2 Gigabit) } else { bandwidth[instanceTypeData] = int64(lo.Must(strconv.ParseFloat(bandwidthSlice[0], 64)) * 1000) } } // collect any remaining instancetypes for _, row := range doc.Find(selector).NextAllFiltered(".table-container").Eq(1).Find("tbody").Find("tr").Nodes { instanceTypeData := row.FirstChild.NextSibling.FirstChild.FirstChild.Data bandwidthData := row.FirstChild.NextSibling.NextSibling.NextSibling.FirstChild.Data bandwidth[instanceTypeData] = int64(lo.Must(strconv.ParseFloat(bandwidthData, 64)) * 1000) } }() } if err := os.Setenv("AWS_SDK_LOAD_CONFIG", "true"); err != nil { log.Fatalf("setting AWS_SDK_LOAD_CONFIG, %s", err) } if err := os.Setenv("AWS_REGION", "us-east-1"); err != nil { log.Fatalf("setting AWS_REGION, %s", err) } sess := session.Must(session.NewSession()) ec2api := ec2.New(sess) instanceTypesOutput := lo.Must(ec2api.DescribeInstanceTypes(&ec2.DescribeInstanceTypesInput{})) allInstanceTypes := lo.Map(instanceTypesOutput.InstanceTypes, func(info *ec2.InstanceTypeInfo, _ int) string { return *info.InstanceType }) instanceTypes := lo.Keys(bandwidth) // 2d sort for readability sort.Strings(allInstanceTypes) sort.Strings(instanceTypes) sort.SliceStable(instanceTypes, func(i, j int) bool { return bandwidth[instanceTypes[i]] < bandwidth[instanceTypes[j]] }) // Generate body var body string for _, instanceType := range lo.Without(allInstanceTypes, instanceTypes...) { body += fmt.Sprintf("// %s is not available in https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-network-bandwidth.html\n", instanceType) } for _, instanceType := range instanceTypes { body += fmt.Sprintf("\t\"%s\": %d,\n", instanceType, bandwidth[instanceType]) } license := lo.Must(os.ReadFile("hack/boilerplate.go.txt")) // Format and print to the file formatted := lo.Must(format.Source([]byte(fmt.Sprintf(fileFormat, license, body)))) file := lo.Must(os.Create(flag.Args()[0])) lo.Must(file.Write(formatted)) file.Close() } func containsAny(value string, excludedSubstrings ...string) bool { for _, str := range excludedSubstrings { if strings.Contains(value, str) { return true } } return false }
148
karpenter
aws
Go
/* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package main import ( "bytes" "context" "flag" "fmt" "go/format" "log" "os" "sort" "strings" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/ec2" "github.com/aws/aws-sdk-go/service/ec2/ec2iface" "github.com/samber/lo" ) const packageHeader = ` package fake import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" ) // GENERATED FILE. DO NOT EDIT DIRECTLY. // Update hack/code/instancetype_testdata_gen.go and re-generate to edit // You can add instance types by adding to the --instance-types CLI flag ` var instanceTypesStr string var outFile string func init() { flag.StringVar(&instanceTypesStr, "instance-types", "", "comma-separated list of instance types to auto-generate static test data from") flag.StringVar(&outFile, "out-file", "zz_generated.describe_instance_types.go", "file to output the generated data") flag.Parse() } func main() { if err := os.Setenv("AWS_SDK_LOAD_CONFIG", "true"); err != nil { log.Fatalf("setting AWS_SDK_LOAD_CONFIG, %s", err) } if err := os.Setenv("AWS_REGION", "us-east-1"); err != nil { log.Fatalf("setting AWS_REGION, %s", err) } ctx := context.Background() sess := session.Must(session.NewSession()) ec2Client := ec2.New(sess) instanceTypes := strings.Split(instanceTypesStr, ",") src := &bytes.Buffer{} fmt.Fprintln(src, "//go:build !ignore_autogenerated") license := lo.Must(os.ReadFile("hack/boilerplate.go.txt")) fmt.Fprintln(src, string(license)) fmt.Fprint(src, packageHeader) fmt.Fprintln(src, getDescribeInstanceTypesOutput(ctx, ec2Client, instanceTypes)) // Format and print to the file formatted, err := format.Source(src.Bytes()) if err != nil { log.Fatalf("formatting generated source, %s", err) } if err := os.WriteFile(outFile, formatted, 0644); err != nil { log.Fatalf("writing output, %s", err) } } func getDescribeInstanceTypesOutput(ctx context.Context, ec2Client ec2iface.EC2API, instanceTypes []string) string { out, err := ec2Client.DescribeInstanceTypesWithContext(ctx, &ec2.DescribeInstanceTypesInput{ InstanceTypes: aws.StringSlice(instanceTypes), }) if err != nil { log.Fatalf("describing instance types, %s", err) } // Sort them by name so that we get a consistent ordering sort.SliceStable(out.InstanceTypes, func(i, j int) bool { return aws.StringValue(out.InstanceTypes[i].InstanceType) < aws.StringValue(out.InstanceTypes[j].InstanceType) }) src := &bytes.Buffer{} fmt.Fprintln(src, "var defaultDescribeInstanceTypesOutput = &ec2.DescribeInstanceTypesOutput{") fmt.Fprintln(src, "InstanceTypes: []*ec2.InstanceTypeInfo{") for _, elem := range out.InstanceTypes { fmt.Fprintln(src, "{") data := getInstanceTypeInfo(elem) fmt.Fprintln(src, data) fmt.Fprintln(src, "},") } fmt.Fprintln(src, "},") fmt.Fprintln(src, "}") return src.String() } func getInstanceTypeInfo(info *ec2.InstanceTypeInfo) string { src := &bytes.Buffer{} fmt.Fprintf(src, "InstanceType: aws.String(\"%s\"),\n", lo.FromPtr(info.InstanceType)) fmt.Fprintf(src, "SupportedUsageClasses: aws.StringSlice([]string{%s}),\n", getStringSliceData(info.SupportedUsageClasses)) fmt.Fprintf(src, "SupportedVirtualizationTypes: aws.StringSlice([]string{%s}),\n", getStringSliceData(info.SupportedVirtualizationTypes)) fmt.Fprintf(src, "BurstablePerformanceSupported: aws.Bool(%t),\n", lo.FromPtr(info.BurstablePerformanceSupported)) fmt.Fprintf(src, "BareMetal: aws.Bool(%t),\n", lo.FromPtr(info.BareMetal)) fmt.Fprintf(src, "Hypervisor: aws.String(\"%s\"),\n", lo.FromPtr(info.Hypervisor)) fmt.Fprintf(src, "ProcessorInfo: &ec2.ProcessorInfo{\n") fmt.Fprintf(src, "SupportedArchitectures: aws.StringSlice([]string{%s}),\n", getStringSliceData(info.ProcessorInfo.SupportedArchitectures)) fmt.Fprintf(src, "},\n") fmt.Fprintf(src, "VCpuInfo: &ec2.VCpuInfo{\n") fmt.Fprintf(src, "DefaultCores: aws.Int64(%d),\n", lo.FromPtr(info.VCpuInfo.DefaultCores)) fmt.Fprintf(src, "DefaultVCpus: aws.Int64(%d),\n", lo.FromPtr(info.VCpuInfo.DefaultVCpus)) fmt.Fprintf(src, "},\n") fmt.Fprintf(src, "MemoryInfo: &ec2.MemoryInfo{\n") fmt.Fprintf(src, "SizeInMiB: aws.Int64(%d),\n", lo.FromPtr(info.MemoryInfo.SizeInMiB)) fmt.Fprintf(src, "},\n") if info.InferenceAcceleratorInfo != nil { fmt.Fprintf(src, "InferenceAcceleratorInfo: &ec2.InferenceAcceleratorInfo{\n") fmt.Fprintf(src, "Accelerators: []*ec2.InferenceDeviceInfo{\n") for _, elem := range info.InferenceAcceleratorInfo.Accelerators { fmt.Fprintf(src, getInferenceAcceleratorDeviceInfo(elem)) } fmt.Fprintf(src, "},\n") fmt.Fprintf(src, "},\n") } if info.GpuInfo != nil { fmt.Fprintf(src, "GpuInfo: &ec2.GpuInfo{\n") fmt.Fprintf(src, "Gpus: []*ec2.GpuDeviceInfo{\n") for _, elem := range info.GpuInfo.Gpus { fmt.Fprintf(src, getGPUDeviceInfo(elem)) } fmt.Fprintf(src, "},\n") fmt.Fprintf(src, "},\n") } if info.InstanceStorageInfo != nil { fmt.Fprintf(src, "InstanceStorageInfo: &ec2.InstanceStorageInfo{") fmt.Fprintf(src, "NvmeSupport: aws.String(\"%s\"),\n", lo.FromPtr(info.InstanceStorageInfo.NvmeSupport)) fmt.Fprintf(src, "TotalSizeInGB: aws.Int64(%d),\n", lo.FromPtr(info.InstanceStorageInfo.TotalSizeInGB)) fmt.Fprintf(src, "},\n") } fmt.Fprintf(src, "NetworkInfo: &ec2.NetworkInfo{\n") fmt.Fprintf(src, "MaximumNetworkInterfaces: aws.Int64(%d),\n", lo.FromPtr(info.NetworkInfo.MaximumNetworkInterfaces)) fmt.Fprintf(src, "Ipv4AddressesPerInterface: aws.Int64(%d),\n", lo.FromPtr(info.NetworkInfo.Ipv4AddressesPerInterface)) fmt.Fprintf(src, "EncryptionInTransitSupported: aws.Bool(%t),\n", lo.FromPtr(info.NetworkInfo.EncryptionInTransitSupported)) fmt.Fprintf(src, "DefaultNetworkCardIndex: aws.Int64(%d),\n", lo.FromPtr(info.NetworkInfo.DefaultNetworkCardIndex)) fmt.Fprintf(src, "NetworkCards: []*ec2.NetworkCardInfo{\n") for _, networkCard := range info.NetworkInfo.NetworkCards { fmt.Fprintf(src, getNetworkCardInfo(networkCard)) } fmt.Fprintf(src, "},\n") fmt.Fprintf(src, "},\n") return src.String() } func getNetworkCardInfo(info *ec2.NetworkCardInfo) string { src := &bytes.Buffer{} fmt.Fprintf(src, "{\n") fmt.Fprintf(src, "NetworkCardIndex: aws.Int64(%d),\n", lo.FromPtr(info.NetworkCardIndex)) fmt.Fprintf(src, "MaximumNetworkInterfaces: aws.Int64(%d),\n", lo.FromPtr(info.MaximumNetworkInterfaces)) fmt.Fprintf(src, "},\n") return src.String() } func getInferenceAcceleratorDeviceInfo(info *ec2.InferenceDeviceInfo) string { src := &bytes.Buffer{} fmt.Fprintf(src, "{\n") fmt.Fprintf(src, "Name: aws.String(\"%s\"),\n", lo.FromPtr(info.Name)) fmt.Fprintf(src, "Manufacturer: aws.String(\"%s\"),\n", lo.FromPtr(info.Manufacturer)) fmt.Fprintf(src, "Count: aws.Int64(%d),\n", lo.FromPtr(info.Count)) fmt.Fprintf(src, "},\n") return src.String() } func getGPUDeviceInfo(info *ec2.GpuDeviceInfo) string { src := &bytes.Buffer{} fmt.Fprintf(src, "{\n") fmt.Fprintf(src, "Name: aws.String(\"%s\"),\n", lo.FromPtr(info.Name)) fmt.Fprintf(src, "Manufacturer: aws.String(\"%s\"),\n", lo.FromPtr(info.Manufacturer)) fmt.Fprintf(src, "Count: aws.Int64(%d),\n", lo.FromPtr(info.Count)) fmt.Fprintf(src, "MemoryInfo: &ec2.GpuDeviceMemoryInfo{\n") fmt.Fprintf(src, "SizeInMiB: aws.Int64(%d),\n", lo.FromPtr(info.MemoryInfo.SizeInMiB)) fmt.Fprintf(src, "},\n") fmt.Fprintf(src, "},\n") return src.String() } func getStringSliceData(slice []*string) string { return strings.Join(lo.Map(slice, func(s *string, _ int) string { return fmt.Sprintf(`"%s"`, lo.FromPtr(s)) }), ",") }
205
karpenter
aws
Go
/* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package main import ( "bytes" "context" "flag" "fmt" "go/format" "log" "os" "runtime" "runtime/pprof" "sort" "strings" "time" "github.com/aws/aws-sdk-go/aws/session" ec22 "github.com/aws/aws-sdk-go/service/ec2" "github.com/samber/lo" "k8s.io/apimachinery/pkg/types" "sigs.k8s.io/controller-runtime/pkg/reconcile" "github.com/aws/karpenter/pkg/apis/settings" "github.com/aws/karpenter/pkg/providers/pricing" "github.com/aws/karpenter/pkg/test" ) func main() { flag.Parse() if flag.NArg() != 1 { log.Fatalf("Usage: %s pkg/providers/pricing/zz_generated.pricing.go", os.Args[0]) } f, err := os.Create("pricing.heapprofile") if err != nil { log.Fatal("could not create memory profile: ", err) } defer f.Close() // error handling omitted for example const region = "us-east-1" os.Setenv("AWS_SDK_LOAD_CONFIG", "true") os.Setenv("AWS_REGION", region) ctx := context.Background() ctx = settings.ToContext(ctx, test.Settings()) sess := session.Must(session.NewSession()) ec2 := ec22.New(sess) updateStarted := time.Now() src := &bytes.Buffer{} fmt.Fprintln(src, "//go:build !ignore_autogenerated") license := lo.Must(os.ReadFile("hack/boilerplate.go.txt")) fmt.Fprintln(src, string(license)) fmt.Fprintln(src, "package pricing") fmt.Fprintln(src, `import "time"`) now := time.Now().UTC().Format(time.RFC3339) fmt.Fprintf(src, "// generated at %s for %s\n\n\n", now, region) fmt.Fprintf(src, "var initialPriceUpdate, _ = time.Parse(time.RFC3339, \"%s\")\n", now) fmt.Fprintln(src, "var initialOnDemandPrices = map[string]map[string]float64{}") fmt.Fprintln(src, "func init() {") // record prices for each region we are interested in for _, region := range []string{"us-east-1", "us-gov-west-1", "us-gov-east-1", "cn-north-1"} { log.Println("fetching for", region) pricingProvider := pricing.NewProvider(ctx, pricing.NewAPI(sess, region), ec2, region) controller := pricing.NewController(pricingProvider) _, err := controller.Reconcile(ctx, reconcile.Request{NamespacedName: types.NamespacedName{}}) if err != nil { log.Fatalf("failed to initialize pricing provider %s", err) } for { if pricingProvider.OnDemandLastUpdated().After(updateStarted) && pricingProvider.SpotLastUpdated().After(updateStarted) { break } log.Println("waiting on pricing update...") time.Sleep(1 * time.Second) } instanceTypes := pricingProvider.InstanceTypes() sort.Strings(instanceTypes) writePricing(src, instanceTypes, region, pricingProvider.OnDemandPrice) } fmt.Fprintln(src, "}") formatted, err := format.Source(src.Bytes()) if err != nil { if err := os.WriteFile(flag.Arg(0), src.Bytes(), 0644); err != nil { log.Fatalf("writing output, %s", err) } log.Fatalf("formatting generated source, %s", err) } if err := os.WriteFile(flag.Arg(0), formatted, 0644); err != nil { log.Fatalf("writing output, %s", err) } runtime.GC() if err := pprof.WriteHeapProfile(f); err != nil { log.Fatal("could not write memory profile: ", err) } } func writePricing(src *bytes.Buffer, instanceNames []string, region string, getPrice func(instanceType string) (float64, bool)) { fmt.Fprintf(src, "// %s\n", region) fmt.Fprintf(src, "initialOnDemandPrices[%q] = map[string]float64{\n", region) lineLen := 0 sort.Strings(instanceNames) previousFamily := "" for _, instanceName := range instanceNames { segs := strings.Split(instanceName, ".") if len(segs) != 2 { log.Fatalf("parsing instance family %s, got %v", instanceName, segs) } price, ok := getPrice(instanceName) if !ok { continue } // separating by family should lead to smaller diffs instead of just breaking at line endings only family := segs[0] if family != previousFamily { previousFamily = family newline(src) fmt.Fprintf(src, "// %s family\n", family) lineLen = 0 } n, err := fmt.Fprintf(src, `"%s":%f, `, instanceName, price) if err != nil { log.Fatalf("error writing, %s", err) } lineLen += n if lineLen > 80 { lineLen = 0 fmt.Fprintln(src) } } fmt.Fprintln(src, "\n}") fmt.Fprintln(src) } // newline adds a newline to src, if it does not currently already end with a newline func newline(src *bytes.Buffer) { contents := src.Bytes() // no content yet, so create the new line if len(contents) == 0 { fmt.Println(src) return } // already has a newline, so don't write a new one if contents[len(contents)-1] == '\n' { return } fmt.Fprintln(src) }
165