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
go-kafka-event-source
aws
Go
// Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. // // 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 sak import "context" // RunStatus encapsulates a cancellable Context for the purposes // of determining whether a sub-process is running or to instruct it halt. type RunStatus struct { ctx context.Context cancel context.CancelFunc } // Creates a RunStatus. If `parent` == nil, context.Background() is used. func NewRunStatus(parent context.Context) RunStatus { if parent == nil { parent = context.Background() } ctx, cancel := context.WithCancel(parent) return RunStatus{ctx, cancel} } func (rs RunStatus) Ctx() context.Context { return rs.ctx } // Creates a new RunStatus by adding key/value to the underlying Context. This is semantically different than Fork as the RunStatus // returned here does not get a new context.CancelFunc, so calling Halt on the returned RunStatus will also halt the receiver. func (rs RunStatus) WithValue(key, value any) RunStatus { return RunStatus{ ctx: context.WithValue(rs.ctx, key, value), cancel: rs.cancel, } } func (rs RunStatus) Err() error { return rs.ctx.Err() } // Returns the RunStatus.Ctx().Done() func (rs RunStatus) Done() <-chan struct{} { return rs.ctx.Done() } // Returns true if the underlying Context has neither timed out or has been canceled. func (rs RunStatus) Running() bool { return rs.ctx.Err() == nil } func (rs RunStatus) Halt() { rs.cancel() } // Creates a new child RunStatus, using the current RunStatus.Ctx() as a parent. // The newly created RunStatus get's a new context.CancelFunc. Calling Halt on the returned RunStatus will not Halt the parent. // The equivalent of calling: // // NewRunStatus(rs.Ctx()) func (rs RunStatus) Fork() RunStatus { return NewRunStatus(rs.Ctx()) }
74
go-kafka-event-source
aws
Go
// Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. // // 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 "sak" (Swiss Army knife) provides some basic util functions package sak_test import ( "context" "fmt" "github.com/aws/go-kafka-event-source/streams/sak" ) type Encoder[T any] func(T) ([]byte, error) func encodeString(s string) ([]byte, error) { return []byte(s), nil } func ExampleMust() { var encode Encoder[string] = encodeString b := sak.Must(encode("Hello World!")) fmt.Println(len(b)) // Output: 12 } func ExampleMinN() { vals := []int{1, 9, 4, 10, -1, 25} min := sak.MinN(vals...) fmt.Println(min) // Output: -1 } func ExampleMaxN() { vals := []int{1, 9, 4, 10, -1, 25} max := sak.MaxN(vals...) fmt.Println(max) // Output: 25 } func ExampleMin() { a := uint16(1) b := uint16(2) min := sak.Min(a, b) fmt.Println(min) // Output: 1 } func ExampleMax() { a := uint16(1) b := uint16(2) max := sak.Max(a, b) fmt.Println(max) // Output: 2 } func newIntArray() []int { return make([]int, 0) } func releaseIntArray(a []int) []int { return a[0:0] } func ExamplePool() { intArrayPool := sak.NewPool(100, newIntArray, releaseIntArray) a := intArrayPool.Borrow() for i := 0; i < 10; i++ { a = append(a, i) } fmt.Println(len(a)) intArrayPool.Release(a) b := intArrayPool.Borrow() fmt.Println(len(b)) // Output: 10 // 0 } func ExampleRunStatus() { parent := sak.NewRunStatus(context.Background()).WithValue("name", "parent") child1 := parent.Fork().WithValue("name", "child1") // will override "name" of parent child2 := parent.Fork() // will inherit "name" from parent child1.Halt() // child1 halts but parent continues to run fmt.Println(parent.Running()) fmt.Println(child1.Running()) fmt.Println(child2.Running()) parent.Halt() // all RunStatus are halted fmt.Println(parent.Running()) fmt.Println(child2.Running()) fmt.Println(parent.Ctx().Value("name")) fmt.Println(child1.Ctx().Value("name")) fmt.Println(child2.Ctx().Value("name")) // Output: true // false // true // false // false // parent // child1 // parent }
118
go-kafka-event-source
aws
Go
// Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. // // 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 sak import "sync" // Pool is a generic alternative to sync.Pool, but more akin to "Free List". It does not function in the same way however. // It is simply a capped list of objects controlled by a mutex. In many situations, this will sak.Pool will outperform // sync.Pool, however the memory management is very rudimentary and does not provide the same benefits. There is however, much less // overhead than a standard sync.Pool. type Pool[T any] struct { mu sync.Mutex freelist []T factory func() T reset func(T) T } // NewPool creates a new free list. // size is the maximum size of the returned free list. `factory` is the function which allocates new objects when necessary. // `resetter` is optional, but when provided, is invoked on `Release`, before returning the object to the pool. func NewPool[T any](size int, factory func() T, resetter func(T) T) *Pool[T] { if resetter == nil { resetter = func(v T) T { return v } } return &Pool[T]{freelist: make([]T, 0, size), factory: factory, reset: resetter} } // Returns an item from the pool. If none are available, invokes `pool.factory` and return the result. func (p *Pool[T]) Borrow() (n T) { p.mu.Lock() index := len(p.freelist) - 1 if index < 0 { p.mu.Unlock() return p.factory() } var empty T n = p.freelist[index] p.freelist[index] = empty p.freelist = p.freelist[:index] p.mu.Unlock() return } // Returns an item to the pool if there is space available. If a `resetter` function is provided, // it is invoked regardless of wether the item is returned to the pool or not. func (p *Pool[T]) Release(n T) (out bool) { n = p.reset(n) p.mu.Lock() if len(p.freelist) < cap(p.freelist) { p.freelist = append(p.freelist, n) out = true } p.mu.Unlock() return }
68
go-kafka-event-source
aws
Go
// Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. // // 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 "sak" (Swiss Army knife) provides some basic util functions package sak import ( "unsafe" ) // Simple utilty for swapping struct T to a ptr T // Wether or not this creates a heap escape is up to the compiler. // This method simply return &v func Ptr[T any](v T) *T { return &v } type Signed interface { ~int | ~int16 | ~int32 | ~int64 | ~int8 } type Unsigned interface { ~uint | ~uint16 | ~uint32 | ~uint64 | uint8 } type Float interface { ~float32 | ~float64 } type Number interface { Signed | Unsigned | Float } type SignedNumber interface { Signed | Float } // A generic version of math.Abs. func Abs[T SignedNumber](a T) T { if a < 0 { return -a } return a } // A generic version of math.Min. func Min[T Number](a, b T) T { if a < b { return a } return b } // A generic version of math.Min with the added bonus of accepting more than 2 arguments. func MinN[T Number](vals ...T) (min T) { if len(vals) == 0 { return } min = vals[0] for i := 1; i < len(vals); i++ { v := vals[i] if v < min { min = v } } return } // A generic version of math.Max. func Max[T Number](a, b T) T { if a > b { return a } return b } // A generic version of math.Max with the added bonus of accepting more than 2 arguments. func MaxN[T Number](vals ...T) (max T) { if len(vals) == 0 { return } max = vals[0] for i := 1; i < len(vals); i++ { v := vals[i] if v > max { max = v } } return } // A utility function that converts a slice of T to a slice of *T. // Useful when you don't want consumer of your package to be able to mutate an argument passed to you, // but you need to mutate it internally (accept a slice of structs, then swap them to pointers). // This methos forces a heap escape via // // ptr := new(T) // // Used internally but exposed for your consumption. func ToPtrSlice[T any](structs []T) []*T { pointers := make([]*T, len(structs)) for i, v := range structs { ptr := new(T) *ptr = v pointers[i] = ptr } return pointers } // The inverse of ToPtrSlice. // Useful when you're doing some type gymnastics. // Not used internally but, seems only correct to supply the inverse. func ToStructSlice[T any](ptrs []*T) []T { pointers := make([]T, len(ptrs)) for i, v := range ptrs { pointers[i] = *v } return pointers } // A utility function that copies a map[K]T. // Useful when you need to iterate over items in a map that is synchronized buy a Mutex. // Used internally but exposed for your consumption. func MapCopy[K comparable, T any](m map[K]T) map[K]T { c := make(map[K]T, len(m)) for k, v := range m { c[k] = v } return c } // A utility function that extracts all values from a map[K]T. // Useful when you need to iterate over items in a map that is synchronized buy a Mutex. // Used internally but exposed for your consumption. func MapValuesToSlice[K comparable, T any](m map[K]T) []T { slice := make([]T, 0, len(m)) for _, v := range m { slice = append(slice, v) } return slice } // A utility function that extracts all keys from a map[K]T. // Useful when you need to iterate over keys in a map that is synchronized buy a Mutex. // Used internally but exposed for your consumption. func MapKeysToSlice[K comparable, T any](m map[K]T) []K { slice := make([]K, 0, len(m)) for k := range m { slice = append(slice, k) } return slice } // Noescape hides a pointer from escape analysis. noescape is // the identity function but escape analysis doesn't think the // output depends on the input. // USE CAREFULLY! // //go:nosplit func Noescape(p unsafe.Pointer) unsafe.Pointer { x := uintptr(unsafe.Pointer(p)) return unsafe.Pointer(x ^ 0) } // A convenience method for panicking on errors. Useful for simplifying code when calling methods that should never error, // or when thre is no way to recover from the error. func Must[T any](item T, err error) T { if err != nil { panic(err) } return item }
185
go-kafka-event-source
aws
Go
// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package sak // yadll - Yet Another Doubly Linked List copied from the Go source. // When will they provide a Generic version of container/list so we can stop copying this code? // Element is an element of a linked list. type Element[T any] struct { // Next and previous pointers in the doubly-linked list of elements. // To simplify the implementation, internally a list l is implemented // as a ring, such that &l.root is both the next element of the last // list element (l.Back()) and the previous element of the first list // element (l.Front()). next, prev *Element[T] // The list to which this element belongs. list *List[T] // The value stored with this element. Value T } // Next returns the next list element or nil. func (e *Element[T]) Next() *Element[T] { if p := e.next; e.list != nil && p != &e.list.root { return p } return nil } // Prev returns the previous list element or nil. func (e *Element[T]) Prev() *Element[T] { if p := e.prev; e.list != nil && p != &e.list.root { return p } return nil } // List represents a doubly linked list. // The zero value for List is an empty list ready to use. type List[T any] struct { root Element[T] // sentinel list element, only &root, root.prev, and root.next are used len int // current list length excluding (this) sentinel element } // Init initializes or clears list l. func (l *List[T]) Init() *List[T] { l.root.next = &l.root l.root.prev = &l.root l.len = 0 return l } // NewList returns an initialized list. func NewList[T any]() *List[T] { return new(List[T]).Init() } // Len returns the number of elements of list l. // The complexity is O(1). func (l *List[T]) Len() int { return l.len } // Front returns the first element of list l or nil if the list is empty. func (l *List[T]) Front() *Element[T] { if l.len == 0 { return nil } return l.root.next } // Back returns the last element of list l or nil if the list is empty. func (l *List[T]) Back() *Element[T] { if l.len == 0 { return nil } return l.root.prev } // lazyInit lazily initializes a zero List value. func (l *List[T]) lazyInit() { if l.root.next == nil { l.Init() } } // insert inserts e after at, increments l.len, and returns e. func (l *List[T]) insert(e, at *Element[T]) *Element[T] { e.prev = at e.next = at.next e.prev.next = e e.next.prev = e e.list = l l.len++ return e } // insertValue is a convenience wrapper for insert(&Element{Value: v}, at). func (l *List[T]) insertValue(v T, at *Element[T]) *Element[T] { return l.insert(&Element[T]{Value: v}, at) } // remove removes e from its list, decrements l.len func (l *List[T]) remove(e *Element[T]) { e.prev.next = e.next e.next.prev = e.prev e.next = nil // avoid memory leaks e.prev = nil // avoid memory leaks e.list = nil l.len-- } // move moves e to next to at. func (l *List[T]) move(e, at *Element[T]) { if e == at { return } e.prev.next = e.next e.next.prev = e.prev e.prev = at e.next = at.next e.prev.next = e e.next.prev = e } // Remove removes e from l if e is an element of list l. // It returns the element value e.Value. // The element must not be nil. func (l *List[T]) Remove(e *Element[T]) T { if e.list == l { // if e.list == l, l must have been initialized when e was inserted // in l or l == nil (e is a zero Element) and l.remove will crash l.remove(e) } return e.Value } // PushFront inserts a new element e with value v at the front of list l and returns e. func (l *List[T]) PushFront(v T) *Element[T] { l.lazyInit() return l.insertValue(v, &l.root) } // PushBack inserts a new element e with value v at the back of list l and returns e. func (l *List[T]) PushBack(v T) *Element[T] { l.lazyInit() return l.insertValue(v, l.root.prev) } // InsertBefore inserts a new element e with value v immediately before mark and returns e. // If mark is not an element of l, the list is not modified. // The mark must not be nil. func (l *List[T]) InsertBefore(v T, mark *Element[T]) *Element[T] { if mark.list != l { return nil } // see comment in List.Remove about initialization of l return l.insertValue(v, mark.prev) } // InsertAfter inserts a new element e with value v immediately after mark and returns e. // If mark is not an element of l, the list is not modified. // The mark must not be nil. func (l *List[T]) InsertAfter(v T, mark *Element[T]) *Element[T] { if mark.list != l { return nil } // see comment in List.Remove about initialization of l return l.insertValue(v, mark) } // MoveToFront moves element e to the front of list l. // If e is not an element of l, the list is not modified. // The element must not be nil. func (l *List[T]) MoveToFront(e *Element[T]) { if e.list != l || l.root.next == e { return } // see comment in List.Remove about initialization of l l.move(e, &l.root) } // MoveToBack moves element e to the back of list l. // If e is not an element of l, the list is not modified. // The element must not be nil. func (l *List[T]) MoveToBack(e *Element[T]) { if e.list != l || l.root.prev == e { return } // see comment in List.Remove about initialization of l l.move(e, l.root.prev) } // MoveBefore moves element e to its new position before mark. // If e or mark is not an element of l, or e == mark, the list is not modified. // The element and mark must not be nil. func (l *List[T]) MoveBefore(e, mark *Element[T]) { if e.list != l || e == mark || mark.list != l { return } l.move(e, mark.prev) } // MoveAfter moves element e to its new position after mark. // If e or mark is not an element of l, or e == mark, the list is not modified. // The element and mark must not be nil. func (l *List[T]) MoveAfter(e, mark *Element[T]) { if e.list != l || e == mark || mark.list != l { return } l.move(e, mark) } // PushBackList inserts a copy of another list at the back of list l. // The lists l and other may be the same. They must not be nil. func (l *List[T]) PushBackList(other *List[T]) { l.lazyInit() for i, e := other.Len(), other.Front(); i > 0; i, e = i-1, e.Next() { l.insertValue(e.Value, l.root.prev) } } // PushFrontList inserts a copy of another list at the front of list l. // The lists l and other may be the same. They must not be nil. func (l *List[T]) PushFrontList(other *List[T]) { l.lazyInit() for i, e := other.Len(), other.Back(); i > 0; i, e = i-1, e.Prev() { l.insertValue(e.Value, &l.root) } }
232
go-kafka-event-source
aws
Go
// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package sak import "testing" func checkListLen[T any](t *testing.T, l *List[T], len int) bool { if n := l.Len(); n != len { t.Errorf("l.Len() = %d, want %d", n, len) return false } return true } func checkListPointers[T any](t *testing.T, l *List[T], es []*Element[T]) { root := &l.root if !checkListLen(t, l, len(es)) { return } // zero length lists must be the zero value or properly initialized (sentinel circle) if len(es) == 0 { if l.root.next != nil && l.root.next != root || l.root.prev != nil && l.root.prev != root { t.Errorf("l.root.next = %p, l.root.prev = %p; both should both be nil or %p", l.root.next, l.root.prev, root) } return } // len(es) > 0 // check internal and external prev/next connections for i, e := range es { prev := root Prev := (*Element[T])(nil) if i > 0 { prev = es[i-1] Prev = prev } if p := e.prev; p != prev { t.Errorf("elt[%d](%p).prev = %p, want %p", i, e, p, prev) } if p := e.Prev(); p != Prev { t.Errorf("elt[%d](%p).Prev() = %p, want %p", i, e, p, Prev) } next := root Next := (*Element[T])(nil) if i < len(es)-1 { next = es[i+1] Next = next } if n := e.next; n != next { t.Errorf("elt[%d](%p).next = %p, want %p", i, e, n, next) } if n := e.Next(); n != Next { t.Errorf("elt[%d](%p).Next() = %p, want %p", i, e, n, Next) } } } func TestList(t *testing.T) { // Single element list { l := NewList[string]() checkListPointers(t, l, []*Element[string]{}) e := l.PushFront("a") checkListPointers(t, l, []*Element[string]{e}) l.MoveToFront(e) checkListPointers(t, l, []*Element[string]{e}) l.MoveToBack(e) checkListPointers(t, l, []*Element[string]{e}) l.Remove(e) checkListPointers(t, l, []*Element[string]{}) } // Bigger list l := NewList[int]() checkListPointers(t, l, []*Element[int]{}) e2 := l.PushFront(2) e1 := l.PushFront(1) e3 := l.PushBack(3) e4 := l.PushBack(4) checkListPointers(t, l, []*Element[int]{e1, e2, e3, e4}) l.Remove(e2) checkListPointers(t, l, []*Element[int]{e1, e3, e4}) l.MoveToFront(e3) // move from middle checkListPointers(t, l, []*Element[int]{e3, e1, e4}) l.MoveToFront(e1) l.MoveToBack(e3) // move from middle checkListPointers(t, l, []*Element[int]{e1, e4, e3}) l.MoveToFront(e3) // move from back checkListPointers(t, l, []*Element[int]{e3, e1, e4}) l.MoveToFront(e3) // should be no-op checkListPointers(t, l, []*Element[int]{e3, e1, e4}) l.MoveToBack(e3) // move from front checkListPointers(t, l, []*Element[int]{e1, e4, e3}) l.MoveToBack(e3) // should be no-op checkListPointers(t, l, []*Element[int]{e1, e4, e3}) e2 = l.InsertBefore(2, e1) // insert before front checkListPointers(t, l, []*Element[int]{e2, e1, e4, e3}) l.Remove(e2) e2 = l.InsertBefore(2, e4) // insert before middle checkListPointers(t, l, []*Element[int]{e1, e2, e4, e3}) l.Remove(e2) e2 = l.InsertBefore(2, e3) // insert before back checkListPointers(t, l, []*Element[int]{e1, e4, e2, e3}) l.Remove(e2) e2 = l.InsertAfter(2, e1) // insert after front checkListPointers(t, l, []*Element[int]{e1, e2, e4, e3}) l.Remove(e2) e2 = l.InsertAfter(2, e4) // insert after middle checkListPointers(t, l, []*Element[int]{e1, e4, e2, e3}) l.Remove(e2) e2 = l.InsertAfter(2, e3) // insert after back checkListPointers(t, l, []*Element[int]{e1, e4, e3, e2}) l.Remove(e2) // Check standard iteration. sum := 0 for e := l.Front(); e != nil; e = e.Next() { sum += e.Value } if sum != 8 { t.Errorf("sum over l = %d, want 8", sum) } // Clear all elements by iterating var next *Element[int] for e := l.Front(); e != nil; e = next { next = e.Next() l.Remove(e) } checkListPointers(t, l, []*Element[int]{}) } func checkList[T int](t *testing.T, l *List[T], es []T) { if !checkListLen(t, l, len(es)) { return } i := 0 for e := l.Front(); e != nil; e = e.Next() { le := e.Value if le != es[i] { t.Errorf("elt[%d].Value = %v, want %v", i, le, es[i]) } i++ } } func TestExtending(t *testing.T) { l1 := NewList[int]() l2 := NewList[int]() l1.PushBack(1) l1.PushBack(2) l1.PushBack(3) l2.PushBack(4) l2.PushBack(5) l3 := NewList[int]() l3.PushBackList(l1) checkList(t, l3, []int{1, 2, 3}) l3.PushBackList(l2) checkList(t, l3, []int{1, 2, 3, 4, 5}) l3 = NewList[int]() l3.PushFrontList(l2) checkList(t, l3, []int{4, 5}) l3.PushFrontList(l1) checkList(t, l3, []int{1, 2, 3, 4, 5}) checkList(t, l1, []int{1, 2, 3}) checkList(t, l2, []int{4, 5}) l3 = NewList[int]() l3.PushBackList(l1) checkList(t, l3, []int{1, 2, 3}) l3.PushBackList(l3) checkList(t, l3, []int{1, 2, 3, 1, 2, 3}) l3 = NewList[int]() l3.PushFrontList(l1) checkList(t, l3, []int{1, 2, 3}) l3.PushFrontList(l3) checkList(t, l3, []int{1, 2, 3, 1, 2, 3}) l3 = NewList[int]() l1.PushBackList(l3) checkList(t, l1, []int{1, 2, 3}) l1.PushFrontList(l3) checkList(t, l1, []int{1, 2, 3}) } func TestRemove(t *testing.T) { l := NewList[int]() e1 := l.PushBack(1) e2 := l.PushBack(2) checkListPointers(t, l, []*Element[int]{e1, e2}) e := l.Front() l.Remove(e) checkListPointers(t, l, []*Element[int]{e2}) l.Remove(e) checkListPointers(t, l, []*Element[int]{e2}) } func TestIssue4103(t *testing.T) { l1 := NewList[int]() l1.PushBack(1) l1.PushBack(2) l2 := NewList[int]() l2.PushBack(3) l2.PushBack(4) e := l1.Front() l2.Remove(e) // l2 should not change because e is not an element of l2 if n := l2.Len(); n != 2 { t.Errorf("l2.Len() = %d, want 2", n) } l1.InsertBefore(8, e) if n := l1.Len(); n != 3 { t.Errorf("l1.Len() = %d, want 3", n) } } func TestIssue6349(t *testing.T) { l := NewList[int]() l.PushBack(1) l.PushBack(2) e := l.Front() l.Remove(e) if e.Value != 1 { t.Errorf("e.value = %d, want 1", e.Value) } if e.Next() != nil { t.Errorf("e.Next() != nil") } if e.Prev() != nil { t.Errorf("e.Prev() != nil") } } func TestMove(t *testing.T) { l := NewList[int]() e1 := l.PushBack(1) e2 := l.PushBack(2) e3 := l.PushBack(3) e4 := l.PushBack(4) l.MoveAfter(e3, e3) checkListPointers(t, l, []*Element[int]{e1, e2, e3, e4}) l.MoveBefore(e2, e2) checkListPointers(t, l, []*Element[int]{e1, e2, e3, e4}) l.MoveAfter(e3, e2) checkListPointers(t, l, []*Element[int]{e1, e2, e3, e4}) l.MoveBefore(e2, e3) checkListPointers(t, l, []*Element[int]{e1, e2, e3, e4}) l.MoveBefore(e2, e4) checkListPointers(t, l, []*Element[int]{e1, e3, e2, e4}) e2, e3 = e3, e2 l.MoveBefore(e4, e1) checkListPointers(t, l, []*Element[int]{e4, e1, e2, e3}) e1, e2, e3, e4 = e4, e1, e2, e3 l.MoveAfter(e4, e1) checkListPointers(t, l, []*Element[int]{e1, e4, e2, e3}) e2, e3, e4 = e4, e2, e3 l.MoveAfter(e2, e3) checkListPointers(t, l, []*Element[int]{e1, e3, e2, e4}) } // Test PushFront, PushBack, PushFrontList, PushBackList with uninitialized List func TestZeroList(t *testing.T) { var l1 = new(List[int]) l1.PushFront(1) checkList(t, l1, []int{1}) var l2 = new(List[int]) l2.PushBack(1) checkList(t, l2, []int{1}) var l3 = new(List[int]) l3.PushFrontList(l1) checkList(t, l3, []int{1}) var l4 = new(List[int]) l4.PushBackList(l2) checkList(t, l4, []int{1}) } // Test that a list l is not modified when calling InsertBefore with a mark that is not an element of l. func TestInsertBeforeUnknownMark(t *testing.T) { var l List[int] l.PushBack(1) l.PushBack(2) l.PushBack(3) l.InsertBefore(1, new(Element[int])) checkList(t, &l, []int{1, 2, 3}) } // Test that a list l is not modified when calling InsertAfter with a mark that is not an element of l. func TestInsertAfterUnknownMark(t *testing.T) { var l List[int] l.PushBack(1) l.PushBack(2) l.PushBack(3) l.InsertAfter(1, new(Element[int])) checkList(t, &l, []int{1, 2, 3}) } // Test that a list l is not modified when calling MoveAfter or MoveBefore with a mark that is not an element of l. func TestMoveUnknownMark(t *testing.T) { var l1 List[int] e1 := l1.PushBack(1) var l2 List[int] e2 := l2.PushBack(2) l1.MoveAfter(e1, e2) checkList(t, &l1, []int{1}) checkList(t, &l2, []int{2}) l1.MoveBefore(e1, e2) checkList(t, &l1, []int{1}) checkList(t, &l2, []int{2}) }
347
go-kafka-event-source
aws
Go
// Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. // // 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 stores_test import ( "fmt" "strings" "github.com/aws/go-kafka-event-source/streams/stores" ) // This example creates a tree with 32 shards (2<<4). // Each tree shard will be sorted by LastName, FirstName in ascending order. func ExampleShardedTree_contact() { type Contact struct { PhoneNumber string FirstName string LastName string } contactSort := func(a, b Contact) bool { res := strings.Compare(a.LastName, b.LastName) if res != 0 { return res < 0 } return a.FirstName < b.FirstName } shardedTree := stores.NewShardedTree(4, stores.StringHash, contactSort) contact := Contact{ PhoneNumber: "+18005551213", FirstName: "Billy", LastName: "Bob", } tree := shardedTree.For(contact.LastName) tree.ReplaceOrInsert(contact) contact.PhoneNumber = "+18005551212" if oldContact, updated := tree.ReplaceOrInsert(contact); updated { fmt.Printf("PhoneNumber updated from %s to %s\n", oldContact.PhoneNumber, contact.PhoneNumber) } // Output: PhoneNumber updated from +18005551213 to +18005551212 } func ExampleShardedTree_string() { shardedTree := stores.NewShardedTree(4, stores.StringHash, stores.StringLess) partionKey := "Foo" item := "Bar" shardedTree.For(partionKey).ReplaceOrInsert(item) } func ExampleShardedTree_number() { shardedTree := stores.NewShardedTree(4, stores.StringHash, stores.NumberLess[int]) partionKey := "Foo" value := 1000 shardedTree.For(partionKey).ReplaceOrInsert(value) }
72
go-kafka-event-source
aws
Go
// Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. // // 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 stores import ( "math/bits" ) type Prioritizable[T any] interface { HasPriorityOver(item T) bool } type PrioritizedItem[T Prioritizable[T]] struct { index int Value T } // MinMaxHeap provides min-max heap operations for any type that // implements heap.Interface. A min-max heap can be used to implement a // double-ended priority queue. // // Min-max heap implementation from the 1986 paper "Min-Max Heaps and // Generalized Priority Queues" by Atkinson et. al. // https://doi.org/10.1145/6617.6621. type MinMaxHeap[T Prioritizable[T]] struct { items []*PrioritizedItem[T] maxed bool } func NewMinMaxHeap[T Prioritizable[T]](items ...T) *MinMaxHeap[T] { pq := &MinMaxHeap[T]{ items: make([]*PrioritizedItem[T], len(items)), } for i, v := range items { pq.items[i] = &PrioritizedItem[T]{index: i, Value: v} } initHeap(pq) return pq } func (pq *MinMaxHeap[T]) less(i, j int) bool { a := pq.items[i] b := pq.items[j] return a.Value.HasPriorityOver(b.Value) } func (pq *MinMaxHeap[T]) swap(i, j int) { // a, b := pq.items[i], pq.items[j] = pq.items[j], pq.items[i] pq.items[i].index = i pq.items[j].index = j } func (pq *MinMaxHeap[T]) Len() int { return len(pq.items) } func (pq *MinMaxHeap[T]) Push(item *PrioritizedItem[T]) { pq.maxed = false push(pq, item) } func (pq *MinMaxHeap[T]) Update(item *PrioritizedItem[T]) { pq.maxed = false fix(pq, item.index) } func (pq *MinMaxHeap[T]) Remove(item *PrioritizedItem[T]) { pq.maxed = false remove(pq, item.index) } func (pq *MinMaxHeap[T]) Min() *PrioritizedItem[T] { if pq.Len() == 0 { return nil } return pq.items[0] } func (pq *MinMaxHeap[T]) Max() *PrioritizedItem[T] { if pq.Len() == 0 { return nil } if !pq.maxed { setMax(pq) pq.maxed = true } return pq.items[pq.Len()-1] } func (pq *MinMaxHeap[T]) PopMin() *PrioritizedItem[T] { if pq.Len() == 0 { return nil } pq.maxed = false return popMin(pq) } func (pq *MinMaxHeap[T]) PopMax() *PrioritizedItem[T] { if pq.Len() == 0 { return nil } if !pq.maxed { setMax(pq) } pq.maxed = false return pq.pop() } func (pq *MinMaxHeap[T]) pop() *PrioritizedItem[T] { n := len(pq.items) - 1 v := pq.items[n] pq.items[n] = nil pq.items = pq.items[0:n] return v } func (pq *MinMaxHeap[T]) push(item *PrioritizedItem[T]) { pq.items = append(pq.items, item) } // Interface copied from the heap package, so code that imports minmaxheap does // not also have to import "container/heap". func level(i int) int { // floor(log2(i + 1)) return bits.Len(uint(i)+1) - 1 } func isMinLevel(i int) bool { return level(i)%2 == 0 } func lchild(i int) int { return i*2 + 1 } func rchild(i int) int { return i*2 + 2 } func parent(i int) int { return (i - 1) / 2 } func hasParent(i int) bool { return i > 0 } func hasGrandparent(i int) bool { return i > 2 } func grandparent(i int) int { return parent(parent(i)) } func down[T Prioritizable[T]](h *MinMaxHeap[T], i, n int) bool { min := isMinLevel(i) i0 := i for { m := i l := lchild(i) if l >= n || l < 0 /* overflow */ { break } if h.less(l, m) == min { m = l } r := rchild(i) if r < n && h.less(r, m) == min { m = r } // grandchildren are contiguous i*4+3+{0,1,2,3} for g := lchild(l); g < n && g <= rchild(r); g++ { if h.less(g, m) == min { m = g } } if m == i { break } h.swap(i, m) if m == l || m == r { break } // m is grandchild p := parent(m) if h.less(p, m) == min { h.swap(m, p) } i = m } return i > i0 } func up[T Prioritizable[T]](h *MinMaxHeap[T], i int) { min := isMinLevel(i) if hasParent(i) { p := parent(i) if h.less(p, i) == min { h.swap(i, p) min = !min i = p } } for hasGrandparent(i) { g := grandparent(i) if h.less(i, g) != min { return } h.swap(i, g) i = g } } // initHeap establishes the heap invariants required by the other routines in this // package. initHeap may be called whenever the heap invariants may have been // invalidated. // The complexity is O(n) where n = h.Len(). func initHeap[T Prioritizable[T]](h *MinMaxHeap[T]) { n := h.Len() for i := n/2 - 1; i >= 0; i-- { down(h, i, n) } } // push pushes the element x onto the heap. // The complexity is O(log n) where n = h.Len(). func push[T Prioritizable[T]](h *MinMaxHeap[T], item *PrioritizedItem[T]) { h.push(item) up(h, h.Len()-1) } // popMin removes and returns the minimum element (according to Less) from the heap. // The complexity is O(log n) where n = h.Len(). func popMin[T Prioritizable[T]](h *MinMaxHeap[T]) *PrioritizedItem[T] { n := h.Len() - 1 h.swap(0, n) down(h, 0, n) return h.pop() } // popMax removes and returns the maximum element (according to Less) from the heap. // The complexity is O(log n) where n = h.Len(). func setMax[T Prioritizable[T]](h *MinMaxHeap[T]) { n := h.Len() i := 0 l := lchild(0) if l < n && !h.less(l, i) { i = l } r := rchild(0) if r < n && !h.less(r, i) { i = r } h.swap(i, n-1) down(h, i, n-1) } // // popMax removes and returns the maximum element (according to Less) from the heap. // // The complexity is O(log n) where n = h.Len(). // func popMax[T Prioritizable[T]](h *MinMaxHeap[T]) *PrioritizedItem[T] { // n := h.Len() // i := 0 // l := lchild(0) // if l < n && !h.less(l, i) { // i = l // } // r := rchild(0) // if r < n && !h.less(r, i) { // i = r // } // h.swap(i, n-1) // down(h, i, n-1) // return h.pop() // } // remove removes and returns the element at index i from the heap. // The complexity is O(log n) where n = h.Len(). func remove[T Prioritizable[T]](h *MinMaxHeap[T], i int) interface{} { n := h.Len() - 1 if n != i { h.swap(i, n) if !down(h, i, n) { up(h, i) } } return h.pop() } // fix re-establishes the heap ordering after the element at index i has // changed its value. Changing the value of the element at index i and then // calling fix is equivalent to, but less expensive than, calling Remove(h, i) // followed by a Push of the new value. // The complexity is O(log n) where n = h.Len(). func fix[T Prioritizable[T]](h *MinMaxHeap[T], i int) { if !down(h, i, h.Len()) { up(h, i) } }
330
go-kafka-event-source
aws
Go
// Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. // // 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 stores import ( "github.com/aws/go-kafka-event-source/streams/sak" "github.com/cespare/xxhash/v2" "github.com/google/btree" ) type HashFunc[T any] func(T) uint64 type LessFunc[T any] btree.LessFunc[T] // For string keys, use this for hashFunc argument to NewShardedTree // Uses "github.com/cespare/xxhash/v2".Sum64String func StringHash(s string) uint64 { return xxhash.Sum64String(s) } // For []byte keys, use this for hashFunc argument to NewShardedTree // Uses "github.com/cespare/xxhash/v2".Sum64 func ByteHash(b []byte) uint64 { return xxhash.Sum64(b) } func StringLess(a, b string) bool { return a < b } func NumberLess[T sak.Number](a, b T) bool { return a < b } // A convenience data structure provided for storing large amounts of data in an in-memory StateStore. // Simply wraps an array of github.com/google/btree#BTreeG[T]. // This is to help alleviate the O(log(n)) performance degerdation of a single, very large tree. // If you need to store more than a million items in a single tree, you might consider using a ShardTree. // There is an upfront O(1) performance hit for calculating the hash of key K when finding a tree. // If you need ordering across your entire data set, this will not fit the bill. type ShardedTree[K any, T any] struct { trees []*btree.BTreeG[T] hashFunc HashFunc[K] mod uint64 } /* Return a ShardedTree. The exponent argument is used to produce the number of shards as follows: shards := 2 << exponent So an exponent of 10 will give you a ShardedTree with 2048 btree.Btree[T] shards. This is to facilitate quicker shard look up with bitwise AND as opposed to a modulo, necessitating a []tree that has a length in an exponent of 2: mod := shards-1 tree := trees[hashFunc(key)&st.mod] Your use case wil determine what the proper number of shards is, but it is recommended to start small -> shards counts between 32-512 (exponents of 4-8). `hashFunc` is used to find a the correct tree for a given key K The `lessFunc`` argument mirrors that required by the "github.com/google/btree" package. The trees in the data ShardedTree will share a common btree.FreeListG[T] */ func NewShardedTree[K any, T any](exponent int, hashFunc HashFunc[K], lessFunc LessFunc[T]) ShardedTree[K, T] { shards := 2 << exponent trees := make([]*btree.BTreeG[T], shards) freeList := btree.NewFreeListG[T](16) for i := 0; i < shards; i++ { trees[i] = btree.NewWithFreeListG(64, (btree.LessFunc[T])(lessFunc), freeList) } return ShardedTree[K, T]{ trees: trees, hashFunc: hashFunc, mod: uint64(shards - 1), } } /* Return the tree for key, invoking the supplied HashFunc[K]. If you're doing multiple operations on the same tree, it makes sense to declare a variable: tree := shardeTree.For(item.key) tree.Delete(item) updateItem(item) tree.ReplaceOrInsert(item) */ func (st ShardedTree[K, T]) For(key K) *btree.BTreeG[T] { return st.trees[st.hashFunc(key)&st.mod] } // Iterates through all trees and sums their lengths. O(n) performance where n = 2 << exponent. func (st ShardedTree[K, T]) Len() (l int) { for _, tree := range st.trees { l += tree.Len() } return }
108
go-kafka-event-source
aws
Go
// Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. // // 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 stores import ( "github.com/aws/go-kafka-event-source/streams" "github.com/aws/go-kafka-event-source/streams/sak" "github.com/google/btree" ) type Keyed interface { Key() string } type keyedValue[T any] struct { key string value T } func keyedLess[T Keyed](a, b *keyedValue[T]) bool { return a.key < b.key } type SimpleStore[T Keyed] struct { tree *btree.BTreeG[*keyedValue[T]] codec streams.Codec[T] topicPartition streams.TopicPartition } func NewJsonSimpleStore[T Keyed](tp streams.TopicPartition) *SimpleStore[T] { return NewSimpleStore[T](tp, streams.JsonCodec[T]{}) } func NewSimpleStore[T Keyed](tp streams.TopicPartition, codec streams.Codec[T]) *SimpleStore[T] { return &SimpleStore[T]{ tree: btree.NewG(64, keyedLess[T]), codec: codec, topicPartition: tp, } } func (s *SimpleStore[T]) ToChangeLogEntry(item T) streams.ChangeLogEntry { return sak.Must(streams.CreateChangeLogEntry(item, s.codec)).WithKeyString(item.Key()) } func (s *SimpleStore[T]) Put(item T) streams.ChangeLogEntry { s.tree.ReplaceOrInsert(&keyedValue[T]{key: item.Key(), value: item}) return s.ToChangeLogEntry(item) } func (s *SimpleStore[T]) Get(id string) (val T, ok bool) { var item *keyedValue[T] key := keyedValue[T]{ key: id, } if item, ok = s.tree.Get(&key); ok { val = item.value } return } func (s *SimpleStore[T]) Delete(item T) (cle streams.ChangeLogEntry, ok bool) { keyedValue := keyedValue[T]{ key: string(item.Key()), } if _, ok = s.tree.Delete(&keyedValue); ok { cle = streams.NewChangeLogEntry().WithKeyString(keyedValue.key) } return } func (s *SimpleStore[T]) ReceiveChange(record streams.IncomingRecord) (err error) { var item T if len(record.Value()) == 0 { keyedValue := keyedValue[T]{ key: string(record.Key()), } s.tree.Delete(&keyedValue) } else if item, err = s.codec.Decode(record.Value()); err != nil { s.tree.ReplaceOrInsert(&keyedValue[T]{key: item.Key(), value: item}) } return } func (s *SimpleStore[T]) Revoked() { s.tree.Clear(false) // not really necessary }
100
iot-atlas
aws
Go
// Copyright 2019 The Hugo Authors. All rights reserved. // // 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 goldmark_config holds Goldmark related configuration. package goldmark_config const ( AutoHeadingIDTypeGitHub = "github" AutoHeadingIDTypeGitHubAscii = "github-ascii" AutoHeadingIDTypeBlackfriday = "blackfriday" ) // DefaultConfig holds the default Goldmark configuration. var Default = Config{ Extensions: Extensions{ Typographer: true, Footnote: true, DefinitionList: true, Table: true, Strikethrough: true, Linkify: true, TaskList: true, Plantuml: true, }, Renderer: Renderer{ Unsafe: false, }, Parser: Parser{ AutoHeadingID: true, AutoHeadingIDType: AutoHeadingIDTypeGitHub, Attribute: ParserAttribute{ Title: true, Block: false, }, }, } // Config configures Goldmark. type Config struct { Renderer Renderer Parser Parser Extensions Extensions } type Extensions struct { Typographer bool Footnote bool DefinitionList bool // GitHub flavored markdown Table bool Strikethrough bool Linkify bool TaskList bool Plantuml bool } type Renderer struct { // Whether softline breaks should be rendered as '<br>' HardWraps bool // XHTML instead of HTML5. XHTML bool // Allow raw HTML etc. Unsafe bool } type Parser struct { // Enables custom heading ids and // auto generated heading ids. AutoHeadingID bool // The strategy to use when generating heading IDs. // Available options are "github", "github-ascii". // Default is "github", which will create GitHub-compatible anchor names. AutoHeadingIDType string // Enables custom attributes. Attribute ParserAttribute } type ParserAttribute struct { // Enables custom attributes for titles. Title bool // Enables custom attributeds for blocks. Block bool }
98
iot-atlas
aws
Go
// Copyright 2019 The Hugo Authors. All rights reserved. // // 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 goldmark converts Markdown to HTML using Goldmark. package goldmark import ( "bytes" "fmt" "math/bits" "path/filepath" "runtime/debug" "github.com/gohugoio/hugo/markup/goldmark/internal/extensions/attributes" "github.com/yuin/goldmark/ast" "github.com/gohugoio/hugo/identity" "github.com/pkg/errors" "github.com/spf13/afero" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/markup/converter" "github.com/gohugoio/hugo/markup/highlight" "github.com/gohugoio/hugo/markup/tableofcontents" "github.com/yuin/goldmark" hl "github.com/yuin/goldmark-highlighting" "github.com/yuin/goldmark/extension" "github.com/yuin/goldmark/parser" "github.com/yuin/goldmark/renderer" "github.com/yuin/goldmark/renderer/html" "github.com/yuin/goldmark/text" "github.com/yuin/goldmark/util" uml "github.com/OhYee/goldmark-plantuml" ) // Provider is the package entry point. var Provider converter.ProviderProvider = provide{} type provide struct { } func (p provide) New(cfg converter.ProviderConfig) (converter.Provider, error) { md := newMarkdown(cfg) return converter.NewProvider("goldmark", func(ctx converter.DocumentContext) (converter.Converter, error) { return &goldmarkConverter{ ctx: ctx, cfg: cfg, md: md, sanitizeAnchorName: func(s string) string { return sanitizeAnchorNameString(s, cfg.MarkupConfig.Goldmark.Parser.AutoHeadingIDType) }, }, nil }), nil } var _ converter.AnchorNameSanitizer = (*goldmarkConverter)(nil) type goldmarkConverter struct { md goldmark.Markdown ctx converter.DocumentContext cfg converter.ProviderConfig sanitizeAnchorName func(s string) string } func (c *goldmarkConverter) SanitizeAnchorName(s string) string { return c.sanitizeAnchorName(s) } func newMarkdown(pcfg converter.ProviderConfig) goldmark.Markdown { mcfg := pcfg.MarkupConfig cfg := pcfg.MarkupConfig.Goldmark var rendererOptions []renderer.Option if cfg.Renderer.HardWraps { rendererOptions = append(rendererOptions, html.WithHardWraps()) } if cfg.Renderer.XHTML { rendererOptions = append(rendererOptions, html.WithXHTML()) } if cfg.Renderer.Unsafe { rendererOptions = append(rendererOptions, html.WithUnsafe()) } var ( extensions = []goldmark.Extender{ newLinks(), newTocExtension(rendererOptions), } parserOptions []parser.Option ) if mcfg.Highlight.CodeFences { extensions = append(extensions, newHighlighting(mcfg.Highlight)) } if cfg.Extensions.Table { extensions = append(extensions, extension.Table) } if cfg.Extensions.Strikethrough { extensions = append(extensions, extension.Strikethrough) } if cfg.Extensions.Linkify { extensions = append(extensions, extension.Linkify) } if cfg.Extensions.TaskList { extensions = append(extensions, extension.TaskList) } if cfg.Extensions.Typographer { extensions = append(extensions, extension.Typographer) } if cfg.Extensions.DefinitionList { extensions = append(extensions, extension.DefinitionList) } if cfg.Extensions.Footnote { extensions = append(extensions, extension.Footnote) } if cfg.Parser.AutoHeadingID { parserOptions = append(parserOptions, parser.WithAutoHeadingID()) } if cfg.Parser.Attribute.Title { parserOptions = append(parserOptions, parser.WithAttribute()) } if cfg.Parser.Attribute.Block { extensions = append(extensions, attributes.New()) } if cfg.Extensions.Plantuml { extensions = append(extensions, uml.Default) } md := goldmark.New( goldmark.WithExtensions( extensions..., ), goldmark.WithParserOptions( parserOptions..., ), goldmark.WithRendererOptions( rendererOptions..., ), ) return md } var _ identity.IdentitiesProvider = (*converterResult)(nil) type converterResult struct { converter.Result toc tableofcontents.Root ids identity.Identities } func (c converterResult) TableOfContents() tableofcontents.Root { return c.toc } func (c converterResult) GetIdentities() identity.Identities { return c.ids } type bufWriter struct { *bytes.Buffer } const maxInt = 1<<(bits.UintSize-1) - 1 func (b *bufWriter) Available() int { return maxInt } func (b *bufWriter) Buffered() int { return b.Len() } func (b *bufWriter) Flush() error { return nil } type renderContext struct { *bufWriter pos int renderContextData } type renderContextData interface { RenderContext() converter.RenderContext DocumentContext() converter.DocumentContext AddIdentity(id identity.Provider) } type renderContextDataHolder struct { rctx converter.RenderContext dctx converter.DocumentContext ids identity.Manager } func (ctx *renderContextDataHolder) RenderContext() converter.RenderContext { return ctx.rctx } func (ctx *renderContextDataHolder) DocumentContext() converter.DocumentContext { return ctx.dctx } func (ctx *renderContextDataHolder) AddIdentity(id identity.Provider) { ctx.ids.Add(id) } var converterIdentity = identity.KeyValueIdentity{Key: "goldmark", Value: "converter"} func (c *goldmarkConverter) Convert(ctx converter.RenderContext) (result converter.Result, err error) { defer func() { if r := recover(); r != nil { dir := afero.GetTempDir(hugofs.Os, "hugo_bugs") name := fmt.Sprintf("goldmark_%s.txt", c.ctx.DocumentID) filename := filepath.Join(dir, name) afero.WriteFile(hugofs.Os, filename, ctx.Src, 07555) fmt.Print(string(debug.Stack())) err = errors.Errorf("[BUG] goldmark: %s: create an issue on GitHub attaching the file in: %s", r, filename) } }() buf := &bufWriter{Buffer: &bytes.Buffer{}} result = buf pctx := c.newParserContext(ctx) reader := text.NewReader(ctx.Src) doc := c.md.Parser().Parse( reader, parser.WithContext(pctx), ) rcx := &renderContextDataHolder{ rctx: ctx, dctx: c.ctx, ids: identity.NewManager(converterIdentity), } w := &renderContext{ bufWriter: buf, renderContextData: rcx, } if err := c.md.Renderer().Render(w, ctx.Src, doc); err != nil { return nil, err } return converterResult{ Result: buf, ids: rcx.ids.GetIdentities(), toc: pctx.TableOfContents(), }, nil } var featureSet = map[identity.Identity]bool{ converter.FeatureRenderHooks: true, } func (c *goldmarkConverter) Supports(feature identity.Identity) bool { return featureSet[feature.GetIdentity()] } func (c *goldmarkConverter) newParserContext(rctx converter.RenderContext) *parserContext { ctx := parser.NewContext(parser.WithIDs(newIDFactory(c.cfg.MarkupConfig.Goldmark.Parser.AutoHeadingIDType))) ctx.Set(tocEnableKey, rctx.RenderTOC) return &parserContext{ Context: ctx, } } type parserContext struct { parser.Context } func (p *parserContext) TableOfContents() tableofcontents.Root { if v := p.Get(tocResultKey); v != nil { return v.(tableofcontents.Root) } return tableofcontents.Root{} } func newHighlighting(cfg highlight.Config) goldmark.Extender { return hl.NewHighlighting( hl.WithStyle(cfg.Style), hl.WithGuessLanguage(cfg.GuessSyntax), hl.WithCodeBlockOptions(highlight.GetCodeBlockOptions()), hl.WithFormatOptions( cfg.ToHTMLOptions()..., ), hl.WithWrapperRenderer(func(w util.BufWriter, ctx hl.CodeBlockContext, entering bool) { l, hasLang := ctx.Language() var language string if hasLang { language = string(l) } if entering { if !ctx.Highlighted() { w.WriteString(`<pre>`) highlight.WriteCodeTag(w, language) return } w.WriteString(`<div class="highlight`) var attributes []ast.Attribute if ctx.Attributes() != nil { attributes = ctx.Attributes().All() } if attributes != nil { class, found := ctx.Attributes().GetString("class") if found { w.WriteString(" ") w.Write(util.EscapeHTML(class.([]byte))) } _, _ = w.WriteString("\"") renderAttributes(w, true, attributes...) } else { _, _ = w.WriteString("\"") } w.WriteString(">") return } if !ctx.Highlighted() { w.WriteString(`</code></pre>`) return } w.WriteString("</div>") }), ) }
364
jsii
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
jsii
aws
Go
package tests import ( "testing" "github.com/aws/jsii-runtime-go" calc "github.com/aws/jsii/jsii-calc/go/jsiicalc/v3" ) func TestPureInterfacesCanBeUsedTransparently(t *testing.T) { requiredstring := "It's Britney b**ch!" expected := calc.StructB{RequiredString: &requiredstring} delegate := &StructReturningDelegate{expected: &expected} consumer := calc.NewConsumePureInterface(delegate) actual := consumer.WorkItBaby() if *actual.RequiredString != *expected.RequiredString { t.Errorf("Expected %v; actual: %v", *expected.RequiredString, *actual.RequiredString) } } func TestPropertyAccessThroughAny(t *testing.T) { any := &ABC{ PropA: "Hello", ProbB: "World", } calc.AnyPropertyAccess_MutateProperties(any, jsii.String("a"), jsii.String("b"), jsii.String("result")) if *any.PropC != "Hello+World" { t.Errorf("Expected Hello+World; actual %v", any.PropC) } } type StructReturningDelegate struct { expected *calc.StructB } func (o *StructReturningDelegate) ReturnStruct() *calc.StructB { return o.expected } type ABC struct { PropA string `json:"a"` ProbB string `json:"b"` PropC *string `json:"result,omitempty"` }
46
jsii
aws
Go
package tests import ( "encoding/json" "io/ioutil" "strings" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" ) type ComplianceSuite struct { suite.Suite _report map[string]map[string]string } func (suite *ComplianceSuite) SetupSuite() { suite._report = map[string]map[string]string{} } func (suite *ComplianceSuite) TearDownSuite() { report, err := json.MarshalIndent(suite._report, "", " ") if err != nil { suite.FailNowf("Failed marshalling _report: %s", err.Error()) } err = ioutil.WriteFile("./compliance-report.json", report, 0644) if err != nil { suite.FailNowf("Failed writing _report: %s", err.Error()) } } func (suite *ComplianceSuite) Require() *require.Assertions { return require.New(suite.T()) } func (suite *ComplianceSuite) reportForTest() map[string]string { fullName := suite.T().Name() testName := strings.Split(fullName, "/")[1] name := strings.Replace(testName, "Test", "", 1) if val, ok := suite._report[name]; ok { return val } val := map[string]string{} suite._report[name] = val return val } func (suite *ComplianceSuite) BeforeTest(suiteName, testName string) { suite.reportForTest()["status"] = "success" } func (suite *ComplianceSuite) skipWithStatus(status string, reason string, url string) { t := suite.T() report := suite.reportForTest() report["status"] = status if reason != "" { report["reason"] = reason } if url != "" { report["url"] = url } t.Skipf("%s: %s", status, reason) } // FailTest will report this test as failing with the URL of the github issue that // reports the bug or missing feature func (suite *ComplianceSuite) FailTest(reason string, issueUrl string) { suite.skipWithStatus("failure", reason, issueUrl) } // NotApplicableTest will report this compliance test as N/A for this language func (suite *ComplianceSuite) NotApplicableTest(reason string) { suite.skipWithStatus("n/a", reason, "") }
82
jsii
aws
Go
package tests import ( "encoding/json" "fmt" "math" "runtime" "testing" "time" "github.com/aws/jsii-runtime-go" "github.com/aws/jsii/go-runtime-test/internal/addTen" "github.com/aws/jsii/go-runtime-test/internal/bellRinger" "github.com/aws/jsii/go-runtime-test/internal/cdk16625" "github.com/aws/jsii/go-runtime-test/internal/doNotOverridePrivates" "github.com/aws/jsii/go-runtime-test/internal/friendlyRandom" "github.com/aws/jsii/go-runtime-test/internal/overrideAsyncMethods" "github.com/aws/jsii/go-runtime-test/internal/syncOverrides" "github.com/aws/jsii/go-runtime-test/internal/twoOverrides" "github.com/aws/jsii/go-runtime-test/internal/wallClock" "github.com/aws/jsii/jsii-calc/go/jcb" calc "github.com/aws/jsii/jsii-calc/go/jsiicalc/v3" "github.com/aws/jsii/jsii-calc/go/jsiicalc/v3/cdk22369" "github.com/aws/jsii/jsii-calc/go/jsiicalc/v3/composition" "github.com/aws/jsii/jsii-calc/go/jsiicalc/v3/submodule/child" calclib "github.com/aws/jsii/jsii-calc/go/scopejsiicalclib" "github.com/aws/jsii/jsii-calc/go/scopejsiicalclib/customsubmodulename" "github.com/aws/jsii/jsii-calc/go/scopejsiicalclib/deprecationremoval" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" ) func (suite *ComplianceSuite) TestStatics() { require := suite.Require() require.Equal("hello ,Yoyo!", *calc.Statics_StaticMethod(jsii.String("Yoyo"))) require.Equal("default", *calc.Statics_Instance().Value()) newStatics := calc.NewStatics(jsii.String("new value")) calc.Statics_SetInstance(newStatics) require.Same(newStatics, calc.Statics_Instance()) require.Equal("new value", *calc.Statics_Instance().Value()) // the float64 conversion is a bit annoying - can we do something about it? require.Equal(float64(100), *calc.Statics_NonConstStatic()) } func (suite *ComplianceSuite) TestPrimitiveTypes() { require := suite.Require() types := calc.NewAllTypes() // boolean types.SetBooleanProperty(jsii.Bool(true)) require.Equal(true, *types.BooleanProperty()) // string types.SetStringProperty(jsii.String("foo")) require.Equal("foo", *types.StringProperty()) // number types.SetNumberProperty(jsii.Number(1234)) require.Equal(float64(1234), *types.NumberProperty()) // json mapProp := map[string]interface{}{"Foo": map[string]interface{}{"Bar": 123}} types.SetJsonProperty(&mapProp) require.Equal(float64(123), (*types.JsonProperty())["Foo"].(map[string]interface{})["Bar"]) types.SetDateProperty(jsii.Time(time.Unix(0, 123000000))) require.WithinDuration(time.Unix(0, 123000000), *types.DateProperty(), 0) } func (suite *ComplianceSuite) TestUseNestedStruct() { jcb.StaticConsumer_Consume(customsubmodulename.NestingClass_NestedStruct{ Name: jsii.String("Bond, James Bond"), }) } func (suite *ComplianceSuite) TestStaticMapInClassCanBeReadCorrectly() { require := suite.Require() result := *calc.ClassWithCollections_StaticMap() require.Equal("value1", *result["key1"]) require.Equal("value2", *result["key2"]) require.Equal(2, len(result)) } func (suite *ComplianceSuite) TestTestNativeObjectsWithInterfaces() { require := suite.Require() // create a pure and native object, not part of the jsii hierarchy, only implements a jsii interface pureNative := newPureNativeFriendlyRandom() generatorBoundToPureNative := calc.NewNumberGenerator(pureNative) require.Equal(pureNative, generatorBoundToPureNative.Generator()) require.Equal(float64(100000), *generatorBoundToPureNative.NextTimes100()) require.Equal(float64(200000), *generatorBoundToPureNative.NextTimes100()) subclassNative := NewSubclassNativeFriendlyRandom() generatorBoundToPSubclassedObject := calc.NewNumberGenerator(subclassNative) require.Equal(subclassNative, generatorBoundToPSubclassedObject.Generator()) generatorBoundToPSubclassedObject.IsSameGenerator(subclassNative) require.Equal(float64(10000), *generatorBoundToPSubclassedObject.NextTimes100()) require.Equal(float64(20000), *generatorBoundToPSubclassedObject.NextTimes100()) } func (suite *ComplianceSuite) TestMaps() { require := suite.Require() // TODO: props should be optional calc2 := calc.NewCalculator(&calc.CalculatorProps{}) calc2.Add(jsii.Number(10)) calc2.Add(jsii.Number(20)) calc2.Mul(jsii.Number(2)) result := *calc2.OperationsMap() require.Equal(2, len(*result["add"])) require.Equal(1, len(*result["mul"])) resultAdd := *result["add"] require.Equal(float64(30), *resultAdd[1].Value()) } func (suite *ComplianceSuite) TestDates() { require := suite.Require() types := calc.NewAllTypes() types.SetDateProperty(jsii.Time(time.Unix(128, 0))) require.WithinDuration(time.Unix(128, 0), *types.DateProperty(), 0) // weak type types.SetAnyProperty(time.Unix(999, 0)) require.WithinDuration(time.Unix(999, 0), types.AnyProperty().(time.Time), 0) } func (suite *ComplianceSuite) TestCallMethods() { require := suite.Require() calc := calc.NewCalculator(&calc.CalculatorProps{}) calc.Add(jsii.Number(10)) require.Equal(float64(10), *calc.Value()) calc.Mul(jsii.Number(2)) require.Equal(float64(20), *calc.Value()) calc.Pow(jsii.Number(5)) require.Equal(float64(20*20*20*20*20), *calc.Value()) calc.Neg() require.Equal(float64(-3200000), *calc.Value()) } func (suite *ComplianceSuite) TestNodeStandardLibrary() { require := suite.Require() obj := calc.NewNodeStandardLibrary() require.Equal("Hello, resource! SYNC!", *obj.FsReadFileSync()) require.NotEmpty(obj.OsPlatform()) require.Equal("6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50", *obj.CryptoSha256()) suite.FailTest("Async methods are not implemented", "https://github.com/aws/jsii/issues/2670") require.Equal("Hello, resource!", obj.FsReadFile()) } func (suite *ComplianceSuite) TestDynamicTypes() { require := suite.Require() types := calc.NewAllTypes() types.SetAnyProperty(false) require.Equal(false, types.AnyProperty()) // string types.SetAnyProperty("String") require.Equal("String", types.AnyProperty()) // number types.SetAnyProperty(12.5) require.Equal(12.5, types.AnyProperty()) // json (notice that when deserialized, it is deserialized as a map). types.SetAnyProperty(map[string]interface{}{ "Goo": []interface{}{ "Hello", map[string]int{ "World": 123, }, }, }) v1 := types.AnyProperty() v2 := v1.(map[string]interface{}) v3 := (v2["Goo"]).([]interface{}) v4 := v3[1] v5 := v4.(map[string]interface{}) v6 := v5["World"].(float64) require.Equal(float64(123), v6) // array types.SetAnyProperty([]string{"Hello", "World"}) a := types.AnyProperty().([]interface{}) require.Equal("Hello", a[0].(string)) require.Equal("World", a[1].(string)) // array of any types.SetAnyProperty([]interface{}{"Hybrid", calclib.NewNumber(jsii.Number(12)), 123, false}) require.Equal(float64(123), (types.AnyProperty()).([]interface{})[2]) // map types.SetAnyProperty(map[string]string{"MapKey": "MapValue"}) require.Equal("MapValue", ((types.AnyProperty()).(map[string]interface{}))["MapKey"]) // map of any types.SetAnyProperty(map[string]interface{}{"Goo": 19289812}) require.Equal(float64(19289812), ((types.AnyProperty()).(map[string]interface{}))["Goo"]) // classes mult := calc.NewMultiply(calclib.NewNumber(jsii.Number(10)), calclib.NewNumber(jsii.Number(20))) types.SetAnyProperty(mult) require.Equal(mult, types.AnyProperty()) require.Equal(float64(200), *((types.AnyProperty()).(calc.Multiply)).Value()) // date types.SetAnyProperty(time.Unix(1234, 0)) require.WithinDuration(time.Unix(1234, 0), types.AnyProperty().(time.Time), 0) } func (suite *ComplianceSuite) TestArrayReturnedByMethodCanBeRead() { require := suite.Require() arr := *calc.ClassWithCollections_CreateAList() require.Contains(arr, jsii.String("one")) require.Contains(arr, jsii.String("two")) } func (suite *ComplianceSuite) TestUnionProperties() { require := suite.Require() calc3 := calc.NewCalculator(&calc.CalculatorProps{ InitialValue: jsii.Number(0), MaximumValue: jsii.Number(math.MaxFloat64), }) calc3.SetUnionProperty(calc.NewMultiply(calclib.NewNumber(jsii.Number(9)), calclib.NewNumber(jsii.Number(3)))) _, ok := calc3.UnionProperty().(calc.Multiply) require.True(ok) require.Equal(float64(9*3), *calc3.ReadUnionValue()) calc3.SetUnionProperty(calc.NewPower(calclib.NewNumber(jsii.Number(10)), calclib.NewNumber(jsii.Number(3)))) _, ok = calc3.UnionProperty().(calc.Power) require.True(ok) } func (suite *ComplianceSuite) TestUseEnumFromScopedModule() { require := suite.Require() obj := calc.NewReferenceEnumFromScopedPackage() require.Equal(calclib.EnumFromScopedModule_VALUE2, obj.Foo()) obj.SetFoo(calclib.EnumFromScopedModule_VALUE1) require.Equal(calclib.EnumFromScopedModule_VALUE1, obj.LoadFoo()) obj.SaveFoo(calclib.EnumFromScopedModule_VALUE2) require.Equal(calclib.EnumFromScopedModule_VALUE2, obj.Foo()) } func (suite *ComplianceSuite) TestCreateObjectAndCtorOverloads() { suite.NotApplicableTest("Golang does not have overloaded functions so the genearated class only has a single New function") } func (suite *ComplianceSuite) TestGetAndSetEnumValues() { require := suite.Require() calc := calc.NewCalculator(&calc.CalculatorProps{}) calc.Add(jsii.Number(9)) calc.Pow(jsii.Number(3)) require.Equal(composition.CompositeOperation_CompositionStringStyle_NORMAL, calc.StringStyle()) calc.SetStringStyle(composition.CompositeOperation_CompositionStringStyle_DECORATED) require.Equal(composition.CompositeOperation_CompositionStringStyle_DECORATED, calc.StringStyle()) require.Equal("<<[[{{(((1 * (0 + 9)) * (0 + 9)) * (0 + 9))}}]]>>", *calc.ToString()) } func (suite *ComplianceSuite) TestListInClassCanBeReadCorrectly() { require := suite.Require() classWithCollections := calc.NewClassWithCollections(&map[string]*string{}, &[]*string{jsii.String("one"), jsii.String("two")}) val := *classWithCollections.Array() require.Equal("one", *val[0]) require.Equal("two", *val[1]) } type derivedFromAllTypes struct { calc.AllTypes } func newDerivedFromAllTypes() derivedFromAllTypes { return derivedFromAllTypes{ calc.NewAllTypes(), } } func (suite *ComplianceSuite) AfterTest(suiteName, testName string) { // Close jsii runtime, clean up the child process, etc... jsii.Close() } func (suite *ComplianceSuite) TestTestFluentApiWithDerivedClasses() { require := suite.Require() obj := newDerivedFromAllTypes() obj.SetStringProperty(jsii.String("Hello")) obj.SetNumberProperty(jsii.Number(12)) require.Equal("Hello", *obj.StringProperty()) require.Equal(float64(12), *obj.NumberProperty()) } func (suite *ComplianceSuite) TestCanLoadEnumValues() { require := suite.Require() require.NotEmpty(calc.EnumDispenser_RandomStringLikeEnum()) require.NotEmpty(calc.EnumDispenser_RandomIntegerLikeEnum()) } func (suite *ComplianceSuite) TestCollectionOfInterfaces_ListOfStructs() { require := suite.Require() list := *calc.InterfaceCollections_ListOfStructs() require.Equal("Hello, I'm String!", *list[0].RequiredString) } func (suite *ComplianceSuite) TestDoNotOverridePrivates_property_getter_public() { require := suite.Require() obj := doNotOverridePrivates.New() require.Equal("privateProperty", *obj.PrivatePropertyValue()) // verify the setter override is not invoked. obj.ChangePrivatePropertyValue(jsii.String("MyNewValue")) require.Equal("MyNewValue", *obj.PrivatePropertyValue()) } func (suite *ComplianceSuite) TestEqualsIsResistantToPropertyShadowingResultVariable() { require := suite.Require() first := calc.StructWithJavaReservedWords{Default: jsii.String("one")} second := calc.StructWithJavaReservedWords{Default: jsii.String("one")} third := calc.StructWithJavaReservedWords{Default: jsii.String("two")} require.Equal(first, second) require.NotEqual(first, third) } type overridableProtectedMemberDerived struct { calc.OverridableProtectedMember } func newOverridableProtectedMemberDerived() *overridableProtectedMemberDerived { o := overridableProtectedMemberDerived{} calc.NewOverridableProtectedMember_Override(&o) return &o } func (x *overridableProtectedMemberDerived) OverrideReadOnly() *string { return jsii.String("Cthulhu ") } func (x *overridableProtectedMemberDerived) OverrideReadWrite() *string { return jsii.String("Fhtagn!") } func (suite *ComplianceSuite) TestCanOverrideProtectedGetter() { require := suite.Require() overridden := newOverridableProtectedMemberDerived() require.Equal("Cthulhu Fhtagn!", *overridden.ValueFromProtected()) } type implementsAdditionalInterface struct { calc.AllTypes _struct calc.StructB } func newImplementsAdditionalInterface(s calc.StructB) *implementsAdditionalInterface { n := implementsAdditionalInterface{_struct: s} calc.NewAllTypes_Override(&n) return &n } func (x *implementsAdditionalInterface) ReturnStruct() *calc.StructB { return &x._struct } func (suite *ComplianceSuite) TestInterfacesCanBeUsedTransparently_WhenAddedToJsiiType() { require := suite.Require() expected := calc.StructB{RequiredString: jsii.String("It's Britney b**ch!")} delegate := newImplementsAdditionalInterface(expected) consumer := calc.NewConsumePureInterface(delegate) require.Equal(expected, *consumer.WorkItBaby()) } func (suite *ComplianceSuite) TestStructs_nonOptionalequals() { require := suite.Require() structA := calc.StableStruct{ReadonlyProperty: jsii.String("one")} structB := calc.StableStruct{ReadonlyProperty: jsii.String("one")} structC := calc.StableStruct{ReadonlyProperty: jsii.String("two")} require.Equal(structB, structA) require.NotEqual(structC, structA) } func (suite *ComplianceSuite) TestTestInterfaceParameter() { require := suite.Require() obj := calc.NewJSObjectLiteralForInterface() friendly := obj.GiveMeFriendly() require.Equal("I am literally friendly!", *friendly.Hello()) greetingAugmenter := calc.NewGreetingAugmenter() betterGreeting := greetingAugmenter.BetterGreeting(friendly) require.Equal("I am literally friendly! Let me buy you a drink!", *betterGreeting) } func (suite *ComplianceSuite) TestLiftedKwargWithSameNameAsPositionalArg() { require := suite.Require() // This is a replication of a test that mostly affects languages with keyword arguments (e.g: Python, Ruby, ...) bell := calc.NewBell() amb := calc.NewAmbiguousParameters(bell, &calc.StructParameterType{Scope: jsii.String("Driiiing!")}) require.Equal(bell, amb.Scope()) expected := calc.StructParameterType{Scope: jsii.String("Driiiing!")} require.Equal(expected, *amb.Props()) } type mulTen struct { calc.Multiply } func newMulTen(value *float64) mulTen { return mulTen{ calc.NewMultiply(calclib.NewNumber(value), calclib.NewNumber(jsii.Number(10))), } } func (suite *ComplianceSuite) TestCreationOfNativeObjectsFromJavaScriptObjects() { require := suite.Require() types := calc.NewAllTypes() jsObj := calclib.NewNumber(jsii.Number(44)) types.SetAnyProperty(jsObj) _, ok := (types.AnyProperty()).(calclib.Number) require.True(ok) suite.FailTest("??", "??") nativeObj := addTen.New(jsii.Number(10)) types.SetAnyProperty(nativeObj) result1 := types.AnyProperty() require.Equal(nativeObj, result1) nativeObj2 := newMulTen(jsii.Number(20)) types.SetAnyProperty(nativeObj2) unmarshalledNativeObj, ok := (types.AnyProperty()).(mulTen) require.True(ok) require.Equal(nativeObj2, unmarshalledNativeObj) } func (suite *ComplianceSuite) TestStructs_ReturnedLiteralEqualsNativeBuilt() { require := suite.Require() gms := calc.NewGiveMeStructs() returnedLiteral := gms.StructLiteral() nativeBuilt := calclib.StructWithOnlyOptionals{ Optional1: jsii.String("optional1FromStructLiteral"), Optional3: jsii.Bool(false), } require.Equal(*nativeBuilt.Optional1, *returnedLiteral.Optional1) require.Equal(nativeBuilt.Optional2, returnedLiteral.Optional2) require.Equal(*nativeBuilt.Optional3, *returnedLiteral.Optional3) require.EqualValues(nativeBuilt, *returnedLiteral) require.EqualValues(*returnedLiteral, nativeBuilt) } func (suite *ComplianceSuite) TestClassesCanSelfReferenceDuringClassInitialization() { require := suite.Require() outerClass := child.NewOuterClass() require.NotNil(outerClass.InnerClass()) } func (suite *ComplianceSuite) TestCanObtainStructReferenceWithOverloadedSetter() { require := suite.Require() require.NotNil(calc.ConfusingToJackson_MakeStructInstance()) } func (suite *ComplianceSuite) TestCallbacksCorrectlyDeserializeArguments() { require := suite.Require() renderer := NewTestCallbacksCorrectlyDeserializeArgumentsDataRenderer() require.Equal("{\n \"anumber\": 50,\n \"astring\": \"50\",\n \"custom\": \"value\"\n}", *renderer.Render(&calclib.MyFirstStruct{Anumber: jsii.Number(50), Astring: jsii.String("50")})) } type testCallbacksCorrectlyDeserializeArgumentsDataRenderer struct { calc.DataRenderer } func NewTestCallbacksCorrectlyDeserializeArgumentsDataRenderer() *testCallbacksCorrectlyDeserializeArgumentsDataRenderer { t := testCallbacksCorrectlyDeserializeArgumentsDataRenderer{} calc.NewDataRenderer_Override(&t) return &t } func (r *testCallbacksCorrectlyDeserializeArgumentsDataRenderer) RenderMap(m *map[string]interface{}) *string { mapInput := *m mapInput["custom"] = jsii.String("value") // this is here to make sure this override actually gets invoked. return r.DataRenderer.RenderMap(m) } func (suite *ComplianceSuite) TestCanUseInterfaceSetters() { require := suite.Require() obj := calc.ObjectWithPropertyProvider_Provide() obj.SetProperty(jsii.String("New Value")) require.True(*obj.WasSet()) } func (suite *ComplianceSuite) TestPropertyOverrides_Interfaces() { require := suite.Require() interfaceWithProps := TestPropertyOverridesInterfacesIInterfaceWithProperties{} interact := calc.NewUsesInterfaceWithProperties(&interfaceWithProps) require.Equal("READ_ONLY_STRING", *interact.JustRead()) require.Equal("Hello!?", *interact.WriteAndRead(jsii.String("Hello"))) } type TestPropertyOverridesInterfacesIInterfaceWithProperties struct { x *string } func (i *TestPropertyOverridesInterfacesIInterfaceWithProperties) ReadOnlyString() *string { return jsii.String("READ_ONLY_STRING") } func (i *TestPropertyOverridesInterfacesIInterfaceWithProperties) ReadWriteString() *string { strct := *i str := *strct.x result := str + "?" return jsii.String(result) } func (i *TestPropertyOverridesInterfacesIInterfaceWithProperties) SetReadWriteString(value *string) { newVal := *value + "!" i.x = &newVal } func (suite *ComplianceSuite) TestTestJsiiAgent() { require := suite.Require() require.Equal(fmt.Sprintf("%s/%s/%s", runtime.Version(), runtime.GOOS, runtime.GOARCH), *calc.JsiiAgent_Value()) } func (suite *ComplianceSuite) TestDoNotOverridePrivates_Method_Private() { require := suite.Require() obj := &TestDoNotOverridePrivatesMethodPrivateDoNotOverridePrivates{ DoNotOverridePrivates: calc.NewDoNotOverridePrivates(), } require.Equal("privateMethod", *obj.PrivateMethodValue()) } type TestDoNotOverridePrivatesMethodPrivateDoNotOverridePrivates struct { calc.DoNotOverridePrivates } func (d *TestDoNotOverridePrivatesMethodPrivateDoNotOverridePrivates) privateMethod() string { return "privateMethod-Override" } func (suite *ComplianceSuite) TestPureInterfacesCanBeUsedTransparently() { require := suite.Require() expected := &calc.StructB{ RequiredString: jsii.String("It's Britney b**ch!"), } delegate := &TestPureInterfacesCanBeUsedTransparentlyIStructReturningDelegate{ expected: expected, } consumer := calc.NewConsumePureInterface(delegate) require.EqualValues(expected, consumer.WorkItBaby()) } type TestPureInterfacesCanBeUsedTransparentlyIStructReturningDelegate struct { expected *calc.StructB } func (t *TestPureInterfacesCanBeUsedTransparentlyIStructReturningDelegate) ReturnStruct() *calc.StructB { return t.expected } func (suite *ComplianceSuite) TestNullShouldBeTreatedAsUndefined() { obj := calc.NewNullShouldBeTreatedAsUndefined(jsii.String("hello"), nil) obj.GiveMeUndefined(nil) obj.GiveMeUndefinedInsideAnObject(&calc.NullShouldBeTreatedAsUndefinedData{ ThisShouldBeUndefined: nil, ArrayWithThreeElementsAndUndefinedAsSecondArgument: &[]interface{}{jsii.String("hello"), nil, jsii.String("boom")}, }) var nilstr *string obj.SetChangeMeToUndefined(nilstr) obj.VerifyPropertyIsUndefined() } type myOverridableProtectedMember struct { calc.OverridableProtectedMember } func newMyOverridableProtectedMember() *myOverridableProtectedMember { m := myOverridableProtectedMember{} calc.NewOverridableProtectedMember_Override(&m) return &m } func (x *myOverridableProtectedMember) OverrideMe() *string { return jsii.String("Cthulhu Fhtagn!") } func (suite *ComplianceSuite) TestCanOverrideProtectedMethod() { require := suite.Require() challenge := "Cthulhu Fhtagn!" overridden := newMyOverridableProtectedMember() require.Equal(challenge, *overridden.ValueFromProtected()) } func (suite *ComplianceSuite) TestEraseUnsetDataValues() { require := suite.Require() opts := calc.EraseUndefinedHashValuesOptions{Option1: jsii.String("option1")} require.True(*calc.EraseUndefinedHashValues_DoesKeyExist(&opts, jsii.String("option1"))) require.Equal(map[string]interface{}{"prop2": "value2"}, *calc.EraseUndefinedHashValues_Prop1IsNull()) require.Equal(map[string]interface{}{"prop1": "value1"}, *calc.EraseUndefinedHashValues_Prop2IsUndefined()) require.False(*calc.EraseUndefinedHashValues_DoesKeyExist(&opts, jsii.String("option2"))) } func (suite *ComplianceSuite) TestStructs_containsNullChecks() { require := suite.Require() s := calclib.MyFirstStruct{} // <-- this struct has required fields obj := calc.NewGiveMeStructs() suite.FailTest("No validation of required fields in structs", "https://github.com/aws/jsii/issues/2672") // we expect a failure here when we pass the struct to js require.PanicsWithError("", func() { obj.ReadFirstNumber(&s) }) } func (suite *ComplianceSuite) TestUnionPropertiesWithBuilder() { require := suite.Require() obj1 := calc.UnionProperties{Bar: 12, Foo: "Hello"} require.Equal(12, obj1.Bar) require.Equal("Hello", obj1.Foo) obj2 := calc.UnionProperties{Bar: "BarIsString"} require.Equal("BarIsString", obj2.Bar) require.Empty(obj2.Foo) allTypes := calc.NewAllTypes() obj3 := calc.UnionProperties{Bar: allTypes, Foo: 999} require.Same(allTypes, obj3.Bar) require.Equal(999, obj3.Foo) } func (suite *ComplianceSuite) TestTestNullIsAValidOptionalMap() { require := suite.Require() require.Nil(calc.DisappointingCollectionSource_MaybeMap()) } func (suite *ComplianceSuite) TestMapReturnedByMethodCanBeRead() { require := suite.Require() result := *calc.ClassWithCollections_CreateAMap() require.Equal("value1", *result["key1"]) require.Equal("value2", *result["key2"]) require.Equal(2, len(result)) } type myAbstractSuite struct { calc.AbstractSuite _property *string } func NewMyAbstractSuite(prop *string) *myAbstractSuite { m := myAbstractSuite{_property: prop} calc.NewAbstractSuite_Override(&m) return &m } func (s *myAbstractSuite) SomeMethod(str *string) *string { return jsii.String(fmt.Sprintf("Wrapped<%s>", *str)) } func (s *myAbstractSuite) Property() *string { return s._property } func (s *myAbstractSuite) SetProperty(value *string) { v := fmt.Sprintf("String<%s>", *value) s._property = &v } func (suite *ComplianceSuite) TestAbstractMembersAreCorrectlyHandled() { require := suite.Require() abstractSuite := NewMyAbstractSuite(nil) require.Equal("Wrapped<String<Oomf!>>", *abstractSuite.WorkItAll(jsii.String("Oomf!"))) } func (suite *ComplianceSuite) TestCanOverrideProtectedSetter() { require := suite.Require() challenge := "Bazzzzzzzzzzzaar..." overridden := newTestCanOverrideProtectedSetterOverridableProtectedMember() overridden.SwitchModes() require.Equal(challenge, *overridden.ValueFromProtected()) } type TestCanOverrideProtectedSetterOverridableProtectedMember struct { calc.OverridableProtectedMember } func (x *TestCanOverrideProtectedSetterOverridableProtectedMember) SetOverrideReadWrite(val *string) { x.OverridableProtectedMember.SetOverrideReadWrite(jsii.String(fmt.Sprintf("zzzzzzzzz%s", *val))) } func newTestCanOverrideProtectedSetterOverridableProtectedMember() *TestCanOverrideProtectedSetterOverridableProtectedMember { m := TestCanOverrideProtectedSetterOverridableProtectedMember{} calc.NewOverridableProtectedMember_Override(&m) return &m } func (suite *ComplianceSuite) TestObjRefsAreLabelledUsingWithTheMostCorrectType() { require := suite.Require() ifaceRef := calc.Constructors_MakeInterface() v := ifaceRef require.NotNil(v) // TODO: I am not sure this is possible in Go (probably N/A) suite.FailTest("N/A?", "") classRef, ok := calc.Constructors_MakeClass().(calc.InbetweenClass) require.True(ok) require.NotNil(classRef) } func (suite *ComplianceSuite) TestStructs_StepBuilders() { suite.NotApplicableTest("Go does not generate fluent builders") } func (suite *ComplianceSuite) TestStaticListInClassCannotBeModified() { suite.NotApplicableTest("Go arrays are immutable by design") } func (suite *ComplianceSuite) TestStructsAreUndecoratedOntheWayToKernel() { require := suite.Require() s := calc.StructB{RequiredString: jsii.String("Bazinga!"), OptionalBoolean: jsii.Bool(false)} j := calc.JsonFormatter_Stringify(s) var a map[string]interface{} if err := json.Unmarshal([]byte(*j), &a); err != nil { require.FailNowf(err.Error(), "unmarshal failed") } require.Equal( map[string]interface{}{ "requiredString": "Bazinga!", "optionalBoolean": false, }, a, ) } func (suite *ComplianceSuite) TestReturnAbstract() { require := suite.Require() obj := calc.NewAbstractClassReturner() obj2 := obj.GiveMeAbstract() require.Equal("Hello, John!!", *obj2.AbstractMethod(jsii.String("John"))) require.Equal("propFromInterfaceValue", *obj2.PropFromInterface()) require.Equal(float64(42), *obj2.NonAbstractMethod()) iface := obj.GiveMeInterface() require.Equal("propFromInterfaceValue", *iface.PropFromInterface()) require.Equal("hello-abstract-property", *obj.ReturnAbstractFromProperty().AbstractProperty()) } func (suite *ComplianceSuite) TestCollectionOfInterfaces_MapOfInterfaces() { mymap := *calc.InterfaceCollections_MapOfInterfaces() for _, value := range mymap { value.Ring() } } func (suite *ComplianceSuite) TestStructs_multiplePropertiesEquals() { require := suite.Require() structA := calc.DiamondInheritanceTopLevelStruct{ BaseLevelProperty: jsii.String("one"), FirstMidLevelProperty: jsii.String("two"), SecondMidLevelProperty: jsii.String("three"), TopLevelProperty: jsii.String("four"), } structB := calc.DiamondInheritanceTopLevelStruct{ BaseLevelProperty: jsii.String("one"), FirstMidLevelProperty: jsii.String("two"), SecondMidLevelProperty: jsii.String("three"), TopLevelProperty: jsii.String("four"), } structC := calc.DiamondInheritanceTopLevelStruct{ BaseLevelProperty: jsii.String("one"), FirstMidLevelProperty: jsii.String("two"), SecondMidLevelProperty: jsii.String("different"), TopLevelProperty: jsii.String("four"), } require.Equal(structA, structB) require.NotEqual(structA, structC) } func (suite *ComplianceSuite) TestAsyncOverrides_callAsyncMethod() { suite.FailTest("Async methods are not implemented", "https://github.com/aws/jsii/issues/2670") require := suite.Require() obj := calc.NewAsyncVirtualMethods() require.Equal(float64(128), *obj.CallMe()) require.Equal(float64(528), *obj.OverrideMe(jsii.Number(44))) } type myDoNotOverridePrivates struct { calc.DoNotOverridePrivates } func (s *myDoNotOverridePrivates) PrivateProperty() string { return "privateProperty-Override" } func (s *myDoNotOverridePrivates) SetPrivateProperty(value string) { panic("Boom") } func (suite *ComplianceSuite) TestDoNotOverridePrivates_property_getter_private() { require := suite.Require() obj := myDoNotOverridePrivates{calc.NewDoNotOverridePrivates()} require.Equal("privateProperty", *obj.PrivatePropertyValue()) // verify the setter override is not invoked. obj.ChangePrivatePropertyValue(jsii.String("MyNewValue")) require.Equal("MyNewValue", *obj.PrivatePropertyValue()) } func (suite *ComplianceSuite) TestStructs_withDiamondInheritance_correctlyDedupeProperties() { require := suite.Require() s := calc.DiamondInheritanceTopLevelStruct{ BaseLevelProperty: jsii.String("base"), FirstMidLevelProperty: jsii.String("mid1"), SecondMidLevelProperty: jsii.String("mid2"), TopLevelProperty: jsii.String("top"), } require.Equal("base", *s.BaseLevelProperty) require.Equal("mid1", *s.FirstMidLevelProperty) require.Equal("mid2", *s.SecondMidLevelProperty) require.Equal("top", *s.TopLevelProperty) } type myDoNotOverridePrivates2 struct { calc.DoNotOverridePrivates } func (s *myDoNotOverridePrivates2) PrivateProperty() string { return "privateProperty-Override" } func (suite *ComplianceSuite) TestDoNotOverridePrivates_property_by_name_private() { require := suite.Require() obj := myDoNotOverridePrivates2{calc.NewDoNotOverridePrivates()} require.Equal("privateProperty", *obj.PrivatePropertyValue()) } func (suite *ComplianceSuite) TestMapInClassCanBeReadCorrectly() { require := suite.Require() modifiableMap := map[string]*string{ "key": jsii.String("value"), } classWithCollections := calc.NewClassWithCollections(&modifiableMap, &[]*string{}) result := *classWithCollections.Map() require.Equal("value", *result["key"]) require.Equal(1, len(result)) } type myAsyncVirtualMethods struct { calc.AsyncVirtualMethods } func (s *myAsyncVirtualMethods) OverrideMe(mult float64) { panic("Thrown by native code") } func (suite *ComplianceSuite) TestAsyncOverrides_overrideThrows() { suite.FailTest("Async methods are not implemented", "https://github.com/aws/jsii/issues/2670") require := suite.Require() obj := myAsyncVirtualMethods{calc.NewAsyncVirtualMethods()} obj.CallMe() require.Panics(func() { obj.CallMe() }) } func (suite *ComplianceSuite) TestHashCodeIsResistantToPropertyShadowingResultVariable() { suite.NotApplicableTest("Go does not have HashCode()") } func (suite *ComplianceSuite) TestStructs_MultiplePropertiesHashCode() { suite.NotApplicableTest("Go does not have HashCode()") } func (suite *ComplianceSuite) TestStructs_OptionalHashCode() { suite.NotApplicableTest("Go does not have HashCode()") } func (suite *ComplianceSuite) TestReturnSubclassThatImplementsInterface976() { t := suite.T() obj := calc.SomeTypeJsii976_ReturnReturn() require.Equal(t, 333.0, *obj.Foo()) } func (suite *ComplianceSuite) TestStructs_OptionalEquals() { suite.NotApplicableTest("Go does not have Equals(other)") } func (suite *ComplianceSuite) TestPropertyOverrides_Get_Calls_Super() { t := suite.T() so := &testPropertyOverridesGetCallsSuper{} calc.NewSyncVirtualMethods_Override(so) require.Equal(t, "super:initial value", *so.RetrieveValueOfTheProperty()) require.Equal(t, "super:initial value", *so.TheProperty()) } type testPropertyOverridesGetCallsSuper struct { calc.SyncVirtualMethods } func (t *testPropertyOverridesGetCallsSuper) TheProperty() *string { s := t.SyncVirtualMethods.TheProperty() return jsii.String(fmt.Sprintf("super:%s", *s)) } func (suite *ComplianceSuite) TestUnmarshallIntoAbstractType() { t := suite.T() c := calc.NewCalculator(&calc.CalculatorProps{}) c.Add(jsii.Number(120)) v := c.Curr() require.Equal(t, 120.0, *v.Value()) } func (suite *ComplianceSuite) TestFail_SyncOverrides_CallsDoubleAsync_PropertyGetter() { t := suite.T() obj := syncOverrides.New() obj.CallAsync = true defer func() { err := recover() require.NotNil(t, err, "expected a failure to occur") }() obj.CallerIsProperty() } func (suite *ComplianceSuite) TestFail_SyncOverrides_CallsDoubleAsync_PropertySetter() { t := suite.T() obj := syncOverrides.New() obj.CallAsync = true defer func() { err := recover() require.NotNil(t, err, "expected a failure to occur") }() obj.SetCallerIsProperty(jsii.Number(12)) } func (suite *ComplianceSuite) TestPropertyOverrides_Get_Set() { t := suite.T() so := syncOverrides.New() require.Equal(t, "I am an override!", *so.RetrieveValueOfTheProperty()) so.ModifyValueOfTheProperty(jsii.String("New Value")) require.Equal(t, "New Value", *so.AnotherTheProperty) } func (suite *ComplianceSuite) TestVariadicMethodCanBeInvoked() { t := suite.T() vm := calc.NewVariadicMethod(jsii.Number(1)) result := vm.AsArray(jsii.Number(3), jsii.Number(4), jsii.Number(5), jsii.Number(6)) require.Equal(t, []*float64{jsii.Number(1), jsii.Number(3), jsii.Number(4), jsii.Number(5), jsii.Number(6)}, *result) } func (suite *ComplianceSuite) TestCollectionTypes() { t := suite.T() at := calc.NewAllTypes() // array at.SetArrayProperty(&[]*string{jsii.String("Hello"), jsii.String("World")}) require.Equal(t, "World", *(*at.ArrayProperty())[1]) // map at.SetMapProperty(&map[string]calclib.Number{"Foo": calclib.NewNumber(jsii.Number(123))}) require.Equal(t, 123.0, *(*at.MapProperty())["Foo"].Value()) } func (suite *ComplianceSuite) TestAsyncOverrides_OverrideAsyncMethodByParentClass() { t := suite.T() obj := overrideAsyncMethods.NewOverrideAsyncMethodsByBaseClass() suite.FailTest("Async methods are not implemented", "https://github.com/aws/jsii/issues/2670") require.Equal(t, 4452.0, obj.CallMe()) } func (suite *ComplianceSuite) TestTestStructsCanBeDowncastedToParentType() { t := suite.T() require.NotZero(t, calc.Demonstrate982_TakeThis()) require.NotZero(t, calc.Demonstrate982_TakeThisToo()) } func (suite *ComplianceSuite) TestPropertyOverrides_Get_Throws() { t := suite.T() so := &testPropertyOverridesGetThrows{} calc.NewSyncVirtualMethods_Override(so) defer func() { err := recover() require.NotNil(t, err, "expected an error!") if e, ok := err.(error); ok { err = e.Error() } require.Equal(t, "Oh no, this is bad", err) }() so.RetrieveValueOfTheProperty() } type testPropertyOverridesGetThrows struct { calc.SyncVirtualMethods } func (t *testPropertyOverridesGetThrows) TheProperty() *string { panic("Oh no, this is bad") } func (suite *ComplianceSuite) TestGetSetPrimitiveProperties() { t := suite.T() number := calclib.NewNumber(jsii.Number(20)) require.Equal(t, 20.0, *number.Value()) require.Equal(t, 40.0, *number.DoubleValue()) require.Equal(t, -30.0, *calc.NewNegate(calc.NewAdd(calclib.NewNumber(jsii.Number(20)), calclib.NewNumber(jsii.Number(10)))).Value()) require.Equal(t, 20.0, *calc.NewMultiply(calc.NewAdd(calclib.NewNumber(jsii.Number(5)), calclib.NewNumber(jsii.Number(5))), calclib.NewNumber(jsii.Number(2))).Value()) require.Equal(t, 3.0*3*3*3, *calc.NewPower(calclib.NewNumber(jsii.Number(3)), calclib.NewNumber(jsii.Number(4))).Value()) require.Equal(t, 999.0, *calc.NewPower(calclib.NewNumber(jsii.Number(999)), calclib.NewNumber(jsii.Number(1))).Value()) require.Equal(t, 1.0, *calc.NewPower(calclib.NewNumber(jsii.Number(999)), calclib.NewNumber(jsii.Number(0))).Value()) } func (suite *ComplianceSuite) TestGetAndSetNonPrimitiveProperties() { t := suite.T() c := calc.NewCalculator(&calc.CalculatorProps{}) c.Add(jsii.Number(3200000)) c.Neg() c.SetCurr(calc.NewMultiply(calclib.NewNumber(jsii.Number(2)), c.Curr())) require.Equal(t, -6400000.0, *c.Value()) } func (suite *ComplianceSuite) TestReservedKeywordsAreSlugifiedInStructProperties() { t := suite.T() t.Skip("Go reserved words do not collide with identifiers used in API surface") } func (suite *ComplianceSuite) TestDoNotOverridePrivates_Method_Public() { t := suite.T() obj := doNotOverridePrivates.New() require.Equal(t, "privateMethod", *obj.PrivateMethodValue()) } func (suite *ComplianceSuite) TestDoNotOverridePrivates_Property_By_Name_Public() { t := suite.T() obj := doNotOverridePrivates.New() require.Equal(t, "privateProperty", *obj.PrivatePropertyValue()) } func (suite *ComplianceSuite) TestTestNullIsAValidOptionalList() { t := suite.T() require.Nil(t, calc.DisappointingCollectionSource_MaybeList()) } func (suite *ComplianceSuite) TestMapInClassCannotBeModified() { suite.NotApplicableTest("Go maps are immutable by design") } func (suite *ComplianceSuite) TestAsyncOverrides_TwoOverrides() { t := suite.T() obj := twoOverrides.New() suite.FailTest("Async methods are not implemented", "https://github.com/aws/jsii/issues/2670") require.Equal(t, 684.0, obj.CallMe()) } func (suite *ComplianceSuite) TestPropertyOverrides_Set_Calls_Super() { t := suite.T() so := &testPropertyOverridesSetCallsSuper{} calc.NewSyncVirtualMethods_Override(so) so.ModifyValueOfTheProperty(jsii.String("New Value")) require.Equal(t, "New Value:by override", *so.TheProperty()) } type testPropertyOverridesSetCallsSuper struct { calc.SyncVirtualMethods } func (t *testPropertyOverridesSetCallsSuper) SetTheProperty(value *string) { t.SyncVirtualMethods.SetTheProperty(jsii.String(fmt.Sprintf("%s:by override", *value))) } func (suite *ComplianceSuite) TestIso8601DoesNotDeserializeToDate() { t := suite.T() nowAsISO := time.Now().Format(time.RFC3339) w := wallClock.NewWallClock(nowAsISO) entropy := wallClock.NewEntropy(w) require.Equal(t, nowAsISO, *entropy.Increase()) } func (suite *ComplianceSuite) TestCollectionOfInterfaces_ListOfInterfaces() { t := suite.T() for _, obj := range *calc.InterfaceCollections_ListOfInterfaces() { require.Implements(t, (*calc.IBell)(nil), obj) } } func (suite *ComplianceSuite) TestUndefinedAndNull() { t := suite.T() c := calc.NewCalculator(&calc.CalculatorProps{}) require.Nil(t, c.MaxValue()) c.SetMaxValue(nil) } func (suite *ComplianceSuite) TestStructs_SerializeToJsii() { t := suite.T() firstStruct := calclib.MyFirstStruct{ Astring: jsii.String("FirstString"), Anumber: jsii.Number(999), FirstOptional: &[]*string{jsii.String("First"), jsii.String("Optional")}, } doubleTrouble := calc.NewDoubleTrouble() derivedStruct := calc.DerivedStruct{ NonPrimitive: doubleTrouble, Bool: jsii.Bool(false), AnotherRequired: jsii.Time(time.Now()), Astring: jsii.String("String"), Anumber: jsii.Number(1234), FirstOptional: &[]*string{jsii.String("one"), jsii.String("two")}, } gms := calc.NewGiveMeStructs() require.Equal(t, 999.0, *gms.ReadFirstNumber(&firstStruct)) require.Equal(t, 1234.0, *gms.ReadFirstNumber(&calclib.MyFirstStruct{ Anumber: derivedStruct.Anumber, Astring: derivedStruct.Astring, FirstOptional: derivedStruct.FirstOptional, })) require.Equal(t, doubleTrouble, gms.ReadDerivedNonPrimitive(&derivedStruct)) literal := *gms.StructLiteral() require.Equal(t, "optional1FromStructLiteral", *literal.Optional1) require.Equal(t, false, *literal.Optional3) require.Nil(t, literal.Optional2) } func (suite *ComplianceSuite) TestCanObtainReferenceWithOverloadedSetter() { t := suite.T() require.NotNil(t, calc.ConfusingToJackson_MakeInstance()) } func (suite *ComplianceSuite) TestTestJsObjectLiteralToNative() { t := suite.T() obj := calc.NewJSObjectLiteralToNative() obj2 := obj.ReturnLiteral() require.Equal(t, "Hello", *obj2.PropA()) require.Equal(t, 102.0, *obj2.PropB()) } func (suite *ComplianceSuite) TestClassWithPrivateConstructorAndAutomaticProperties() { t := suite.T() obj := calc.ClassWithPrivateConstructorAndAutomaticProperties_Create(jsii.String("Hello"), jsii.String("Bye")) require.Equal(t, "Bye", *obj.ReadWriteString()) obj.SetReadWriteString(jsii.String("Hello")) require.Equal(t, "Hello", *obj.ReadOnlyString()) } func (suite *ComplianceSuite) TestArrayReturnedByMethodCannotBeModified() { suite.NotApplicableTest("Go arrays are immutable by design") } func (suite *ComplianceSuite) TestCorrectlyDeserializesStructUnions() { t := suite.T() a0 := &calc.StructA{ RequiredString: jsii.String("Present!"), OptionalString: jsii.String("Bazinga!"), } a1 := &calc.StructA{ RequiredString: jsii.String("Present!"), OptionalNumber: jsii.Number(1337), } b0 := &calc.StructB{ RequiredString: jsii.String("Present!"), OptionalBoolean: jsii.Bool(true), } b1 := &calc.StructB{ RequiredString: jsii.String("Present!"), OptionalStructA: a1, } require.True(t, *calc.StructUnionConsumer_IsStructA(a0)) require.True(t, *calc.StructUnionConsumer_IsStructA(a1)) require.False(t, *calc.StructUnionConsumer_IsStructA(b0)) require.False(t, *calc.StructUnionConsumer_IsStructA(b1)) require.False(t, *calc.StructUnionConsumer_IsStructB(a0)) require.False(t, *calc.StructUnionConsumer_IsStructB(a1)) require.True(t, *calc.StructUnionConsumer_IsStructB(b0)) require.True(t, *calc.StructUnionConsumer_IsStructB(b1)) } func (suite *ComplianceSuite) TestSubclassing() { t := suite.T() t.Log("This is, in fact, demonstrating wrapping another type (which is more go-ey than extending)") c := calc.NewCalculator(&calc.CalculatorProps{}) c.SetCurr(addTen.New(jsii.Number(33))) c.Neg() require.Equal(t, -43.0, *c.Value()) } func (suite *ComplianceSuite) TestTestInterfaces() { t := suite.T() var ( friendly calclib.IFriendly friendlier calc.IFriendlier randomNumberGenerator calc.IRandomNumberGenerator friendlyRandomGenerator calc.IFriendlyRandomGenerator ) add := calc.NewAdd(calclib.NewNumber(jsii.Number(10)), calclib.NewNumber(jsii.Number(20))) friendly = add // friendlier = add // <-- shouldn't compile since Add implements IFriendly require.Equal(t, "Hello, I am a binary operation. What's your name?", *friendly.Hello()) multiply := calc.NewMultiply(calclib.NewNumber(jsii.Number(10)), calclib.NewNumber(jsii.Number(30))) friendly = multiply friendlier = multiply randomNumberGenerator = multiply // friendlyRandomGenerator = multiply // <-- shouldn't compile require.Equal(t, "Hello, I am a binary operation. What's your name?", *friendly.Hello()) require.Equal(t, "Goodbye from Multiply!", *friendlier.Goodbye()) require.Equal(t, 89.0, *randomNumberGenerator.Next()) friendlyRandomGenerator = calc.NewDoubleTrouble() require.Equal(t, "world", *friendlyRandomGenerator.Hello()) require.Equal(t, 12.0, *friendlyRandomGenerator.Next()) poly := calc.NewPolymorphism() require.Equal(t, "oh, Hello, I am a binary operation. What's your name?", *poly.SayHello(friendly)) require.Equal(t, "oh, world", *poly.SayHello(friendlyRandomGenerator)) require.Equal(t, "oh, I am a native!", *poly.SayHello(friendlyRandom.NewPure())) require.Equal(t, "oh, SubclassNativeFriendlyRandom", *poly.SayHello(friendlyRandom.NewSubclass())) } func (suite *ComplianceSuite) TestReservedKeywordsAreSlugifiedInClassProperties() { suite.NotApplicableTest("Golang doesnt have any reserved words that can be used in public API") } func (suite *ComplianceSuite) TestObjectIdDoesNotGetReallocatedWhenTheConstructorPassesThisOut() { reflector := NewPartiallyInitializedThisConsumerImpl(suite.Require()) calc.NewConstructorPassesThisOut(reflector) } type partiallyInitializedThisConsumerImpl struct { calc.PartiallyInitializedThisConsumer require *require.Assertions } func NewPartiallyInitializedThisConsumerImpl(assert *require.Assertions) *partiallyInitializedThisConsumerImpl { p := partiallyInitializedThisConsumerImpl{require: assert} calc.NewPartiallyInitializedThisConsumer_Override(&p) return &p } func (p *partiallyInitializedThisConsumerImpl) ConsumePartiallyInitializedThis(obj calc.ConstructorPassesThisOut, dt *time.Time, ev calc.AllTypesEnum) *string { epoch := time.Date(1970, time.January, 1, 0, 0, 0, 0, time.UTC) p.require.NotNil(obj) p.require.Equal(epoch, *dt) p.require.Equal(calc.AllTypesEnum_THIS_IS_GREAT, ev) return jsii.String("OK") } func (suite *ComplianceSuite) TestInterfaceBuilder() { require := suite.Require() interact := calc.NewUsesInterfaceWithProperties(&TestInterfaceBuilderIInterfaceWithProperties{value: jsii.String("READ_WRITE")}) require.Equal("READ_ONLY", *interact.JustRead()) require.Equal("Hello", *interact.WriteAndRead(jsii.String("Hello"))) } type TestInterfaceBuilderIInterfaceWithProperties struct { value *string } func (i *TestInterfaceBuilderIInterfaceWithProperties) ReadOnlyString() *string { return jsii.String("READ_ONLY") } func (i *TestInterfaceBuilderIInterfaceWithProperties) ReadWriteString() *string { return i.value } func (i *TestInterfaceBuilderIInterfaceWithProperties) SetReadWriteString(val *string) { i.value = val } func (suite *ComplianceSuite) TestUnionTypes() { require := suite.Require() types := calc.NewAllTypes() // single valued property types.SetUnionProperty(1234) require.Equal(float64(1234), types.UnionProperty()) types.SetUnionProperty("Hello") require.Equal("Hello", types.UnionProperty()) types.SetUnionProperty(calc.NewMultiply(calclib.NewNumber(jsii.Number(2)), calclib.NewNumber(jsii.Number(12)))) multiply, ok := types.UnionProperty().(calc.Multiply) require.True(ok) require.Equal(float64(24), *multiply.Value()) // map m := map[string]interface{}{"Foo": calclib.NewNumber(jsii.Number(99))} types.SetUnionMapProperty(&m) unionMapProp := *types.UnionMapProperty() number, ok := unionMapProp["Foo"].(calclib.Number) require.True(ok) require.Equal(float64(99), *number.Value()) // array a := []interface{}{123, calclib.NewNumber(jsii.Number(33))} types.SetUnionArrayProperty(&a) unionArrayProp := *types.UnionArrayProperty() number, ok = unionArrayProp[1].(calclib.Number) require.True(ok) require.Equal(float64(33), *number.Value()) } func (suite *ComplianceSuite) TestArrays() { require := suite.Require() sum := calc.NewSum() sum.SetParts(&[]calclib.NumericValue{calclib.NewNumber(jsii.Number(5)), calclib.NewNumber(jsii.Number(10)), calc.NewMultiply(calclib.NewNumber(jsii.Number(2)), calclib.NewNumber(jsii.Number(3)))}) require.Equal(float64(10+5+(2*3)), *sum.Value()) require.Equal(float64(5), *(*sum.Parts())[0].Value()) require.Equal(float64(6), *(*sum.Parts())[2].Value()) require.Equal("(((0 + 5) + 10) + (2 * 3))", *sum.ToString()) } func (suite *ComplianceSuite) TestStaticMapInClassCannotBeModified() { suite.NotApplicableTest("Golang does not have unmodifiable maps") } func (suite *ComplianceSuite) TestConsts() { require := suite.Require() require.Equal("hello", *calc.Statics_Foo()) obj := calc.Statics_ConstObj() require.Equal("world", *obj.Hello()) require.Equal(float64(1234), *calc.Statics_BAR()) require.Equal("world", *(*calc.Statics_ZooBar())["hello"]) } func (suite *ComplianceSuite) TestReceiveInstanceOfPrivateClass() { require := suite.Require() require.True(*calc.NewReturnsPrivateImplementationOfInterface().PrivateImplementation().Success()) } func (suite *ComplianceSuite) TestMapReturnedByMethodCannotBeModified() { suite.NotApplicableTest("Golang does not have unmodifiable maps") } func (suite *ComplianceSuite) TestStaticListInClassCanBeReadCorrectly() { require := suite.Require() arr := *calc.ClassWithCollections_StaticArray() require.Contains(arr, jsii.String("one")) require.Contains(arr, jsii.String("two")) } func (suite *ComplianceSuite) TestFluentApi() { suite.NotApplicableTest("Golang props are intentionally not designed to be fluent") } func (suite *ComplianceSuite) TestCanLeverageIndirectInterfacePolymorphism() { provider := calc.NewAnonymousImplementationProvider() require := suite.Require() require.Equal(float64(1337), *provider.ProvideAsClass().Value()) require.Equal(float64(1337), *provider.ProvideAsInterface().Value()) require.Equal("to implement", *provider.ProvideAsInterface().Verb()) } func (suite *ComplianceSuite) TestPropertyOverrides_Set_Throws() { require := suite.Require() so := NewTestPropertyOverrides_Set_ThrowsSyncVirtualMethods() require.Panics(func() { so.ModifyValueOfTheProperty(jsii.String("Hii")) }) } type testPropertyOverrides_Set_ThrowsSyncVirtualMethods struct { calc.SyncVirtualMethods } func NewTestPropertyOverrides_Set_ThrowsSyncVirtualMethods() *testPropertyOverrides_Set_ThrowsSyncVirtualMethods { t := testPropertyOverrides_Set_ThrowsSyncVirtualMethods{} calc.NewSyncVirtualMethods_Override(&t) return &t } func (s *testPropertyOverrides_Set_ThrowsSyncVirtualMethods) SetTheProperty(*string) { panic("Exception from overloaded setter") } func (suite *ComplianceSuite) TestStructs_NonOptionalhashCode() { suite.NotApplicableTest("Golang does not have hashCode") } func (suite *ComplianceSuite) TestTestLiteralInterface() { require := suite.Require() obj := calc.NewJSObjectLiteralForInterface() friendly := obj.GiveMeFriendly() require.Equal("I am literally friendly!", *friendly.Hello()) gen := obj.GiveMeFriendlyGenerator() require.Equal("giveMeFriendlyGenerator", *gen.Hello()) require.Equal(float64(42), *gen.Next()) } func (suite *ComplianceSuite) TestReservedKeywordsAreSlugifiedInMethodNames() { suite.NotApplicableTest("Golang doesnt have any reserved words that can be used in public API") } func (suite *ComplianceSuite) TestPureInterfacesCanBeUsedTransparently_WhenTransitivelyImplementing() { require := suite.Require() expected := calc.StructB{ RequiredString: jsii.String("It's Britney b**ch!"), } delegate := NewIndirectlyImplementsStructReturningDelegate(&expected) consumer := calc.NewConsumePureInterface(delegate) require.EqualValues(expected, *consumer.WorkItBaby()) } func NewIndirectlyImplementsStructReturningDelegate(expected *calc.StructB) calc.IStructReturningDelegate { return &IndirectlyImplementsStructReturningDelegate{ImplementsStructReturningDelegate: ImplementsStructReturningDelegate{expected: expected}} } type IndirectlyImplementsStructReturningDelegate struct { ImplementsStructReturningDelegate } type ImplementsStructReturningDelegate struct { expected *calc.StructB } func (i ImplementsStructReturningDelegate) ReturnStruct() *calc.StructB { return i.expected } func (suite *ComplianceSuite) TestExceptions() { require := suite.Require() calc3 := calc.NewCalculator(&calc.CalculatorProps{InitialValue: jsii.Number(20), MaximumValue: jsii.Number(30)}) calc3.Add(jsii.Number(3)) require.Equal(float64(23), *calc3.Value()) require.PanicsWithError("Error: Operation 33 exceeded maximum value 30", func() { calc3.Add(jsii.Number(10)) }) calc3.SetMaxValue(jsii.Number(40)) calc3.Add(jsii.Number(10)) require.Equal(float64(33), *calc3.Value()) } func (suite *ComplianceSuite) TestSyncOverrides_CallsSuper() { require := suite.Require() obj := syncOverrides.New() obj.ReturnSuper = false obj.Multiplier = 1 require.Equal(float64(10*5), *obj.CallerIsProperty()) obj.ReturnSuper = true // js code returns n * 2 require.Equal(float64(10*2), *obj.CallerIsProperty()) } func (suite *ComplianceSuite) TestAsyncOverrides_OverrideCallsSuper() { require := suite.Require() obj := OverrideCallsSuper{AsyncVirtualMethods: calc.NewAsyncVirtualMethods()} suite.FailTest("Async methods are not implemented", "https://github.com/aws/jsii/issues/2670") require.Equal(1441, *obj.OverrideMe(jsii.Number(12))) require.Equal(1209, *obj.CallMe()) } type OverrideCallsSuper struct { calc.AsyncVirtualMethods } func (o *OverrideCallsSuper) OverrideMe(mult *float64) *float64 { superRet := *o.AsyncVirtualMethods.OverrideMe(mult) return jsii.Number(superRet*10 + 1) } func (suite *ComplianceSuite) TestSyncOverrides() { require := suite.Require() obj := syncOverrides.New() obj.ReturnSuper = false obj.Multiplier = 1 require.Equal(float64(10*5), *obj.CallerIsMethod()) // affect the result obj.Multiplier = 5 require.Equal(float64(10*5*5), *obj.CallerIsMethod()) // verify callbacks are invoked from a property require.Equal(float64(10*5*5), *obj.CallerIsProperty()) } func (suite *ComplianceSuite) TestAsyncOverrides_OverrideAsyncMethod() { require := suite.Require() obj := overrideAsyncMethods.New() suite.FailTest("Async methods are not implemented", "https://github.com/aws/jsii/issues/2670") require.Equal(float64(4452), obj.CallMe()) } func (suite *ComplianceSuite) TestFail_SyncOverrides_CallsDoubleAsync_Method() { suite.Require().Panics(func() { obj := syncOverrides.New() obj.CallAsync = true obj.CallerIsMethod() }) } func (suite *ComplianceSuite) TestCollectionOfInterfaces_MapOfStructs() { require := suite.Require() m := *calc.InterfaceCollections_MapOfStructs() require.Equal("Hello, I'm String!", *(*m["A"]).RequiredString) } func (suite *ComplianceSuite) TestCallbackParameterIsInterface() { require := suite.Require() ringer := bellRinger.New() require.True(*calc.ConsumerCanRingBell_StaticImplementedByObjectLiteral(ringer)) require.True(*calc.ConsumerCanRingBell_StaticImplementedByPrivateClass(ringer)) require.True(*calc.ConsumerCanRingBell_StaticImplementedByPublicClass(ringer)) } func (suite *ComplianceSuite) TestClassCanBeUsedWhenNotExpressedlyLoaded() { cdk16625.New().Test() } func (suite *ComplianceSuite) TestDownCasting() { require := suite.Require() anyValue := calc.SomeTypeJsii976_ReturnAnonymous() var realValue calc.IReturnJsii976 jsii.UnsafeCast(anyValue, &realValue) require.Equal(realValue.Foo(), jsii.Number(1337)) } func (suite *ComplianceSuite) TestStrippedDeprecatedMemberCanBeReceived() { require := suite.Require() require.NotNil(deprecationremoval.InterfaceFactory_Create()) } func (suite *ComplianceSuite) TestExceptionMessage() { require := suite.Require() defer func() { err := recover() require.NotNil(err, "expected a failure to occur") require.Contains(err.(error).Error(), "Cannot find asset") }() cdk22369.NewAcceptsPath(&cdk22369.AcceptsPathProps{SourcePath: jsii.String("A Bad Path")}) } // required to make `go test` recognize the suite. func TestComplianceSuite(t *testing.T) { suite.Run(t, new(ComplianceSuite)) }
1,680
jsii
aws
Go
package tests import ( "fmt" "math" "os" "reflect" "strings" "testing" "github.com/aws/jsii-runtime-go" calc "github.com/aws/jsii/jsii-calc/go/jsiicalc/v3" "github.com/aws/jsii/jsii-calc/go/jsiicalc/v3/submodule/param" returnsParam "github.com/aws/jsii/jsii-calc/go/jsiicalc/v3/submodule/returnsparam" calclib "github.com/aws/jsii/jsii-calc/go/scopejsiicalclib" "github.com/aws/jsii/jsii-calc/go/scopejsiicalclib/customsubmodulename" ) func TestMain(m *testing.M) { status := m.Run() jsii.Close() os.Exit(status) } // Only uses first argument as initial value. This is just a convenience for // tests that want to assert against the initialValue func initCalculator(initialValue float64) calc.Calculator { max := jsii.Number(math.MaxFloat64) return calc.NewCalculator(&calc.CalculatorProps{ InitialValue: &initialValue, MaximumValue: max, }) } func TestCalculator(t *testing.T) { // Object creation t.Run("Object creation", func(t *testing.T) { calculator := initCalculator(0) if reflect.ValueOf(calculator).IsZero() { t.Errorf("Expected calculator object to be valid") } }) t.Run("Property access", func(t *testing.T) { expected := float64(10) calculator := initCalculator(expected) actual := calculator.Value() if *actual != expected { t.Errorf("Expected: %f; Actual %f;", expected, *actual) } }) t.Run("Property mutation", func(t *testing.T) { calculator := initCalculator(float64(0)) var newVal float64 = 12345 currentProps := calclib.NewNumber(&newVal) calculator.SetCurr(currentProps) actual := calculator.Value() if newVal != *actual { t.Errorf("Expected: %f; Actual %f;", newVal, *actual) } }) t.Run("Method with side effect", func(t *testing.T) { initial, factor := float64(10), float64(3) calculator := initCalculator(initial) calculator.Mul(&factor) expectedProduct := initial * factor actualProduct := calculator.Value() if *actualProduct != expectedProduct { t.Errorf("Expected quotient: %f; Actual %f;", expectedProduct, *actualProduct) } }) t.Run("Method returning interface{} has embedded data", func(t *testing.T) { calculator := initCalculator(0) expectedTypeName := "Calculator" actualTypeName := calculator.TypeName() // JSII tells us this return value is an "any" type. Therefore the // value received by go is type `interface{}` and can be further // specialized using reflection. switch retType := actualTypeName.(type) { case string: if actualTypeName != expectedTypeName { t.Errorf("Expected type name: %s; Actual %s", expectedTypeName, actualTypeName) } default: t.Errorf("Expected type: %s; Actual type: %s", "string", retType) } }) t.Run("Method with args and string return type", func(t *testing.T) { calculator := initCalculator(0) lhs, rhs := 10, 3 calculator.SetCurr(calc.NewMultiply( calclib.NewNumber(jsii.Number(10)), calclib.NewNumber(jsii.Number(3)), )) expectedString := fmt.Sprintf("(%d * %d)", lhs, rhs) actualString := *calculator.ToString() if actualString != expectedString { t.Errorf("Expected string: %s; Actual %s;", expectedString, actualString) } }) } func TestUpcasingReflectable(t *testing.T) { delegate := make(map[string]interface{}) key, val := "key1", "value1" delegate[key] = val upReflectable := calc.NewUpcasingReflectable(&delegate) entries := *upReflectable.Entries() if len(entries) != 1 { t.Errorf("Entries expected to have length of: 1; Actual: %d", len(entries)) } actual := *entries[0] keyupper := strings.ToUpper(key) expected := customsubmodulename.ReflectableEntry{Key: &keyupper, Value: &val} if *actual.Key != *expected.Key { t.Errorf("Expected %v; Received: %v", *expected.Key, *actual.Key) } } func TestAllTypes(t *testing.T) { allTypes := calc.NewAllTypes() t.Run("Array property", func(t *testing.T) { expected1, expected2 := "val1", "val2" arrproperty := []*string{jsii.String(expected1), jsii.String(expected2)} allTypes.SetArrayProperty(&arrproperty) actual := *allTypes.ArrayProperty() actual1, actual2 := *actual[0], *actual[1] if actual1 != expected1 || actual2 != expected2 { t.Errorf("Expected Values: %s, %s; Received: %s, %s", expected1, expected2, actual1, actual2) } }) t.Run("Any property", func(t *testing.T) { key, val := "key1", "val1" expected := make(map[string]string) expected[key] = val allTypes.SetAnyProperty(expected) actual := allTypes.AnyProperty() actualVal := reflect.ValueOf(actual) switch actualVal.Kind() { case reflect.Map: extractedVal := reflect.ValueOf(actualVal.MapIndex(reflect.ValueOf(key)).Interface()).String() if extractedVal != val { t.Errorf("Expected map: %s; received: %s", expected, actual) } default: t.Errorf("Expected type: %s; Actual type: %s", "map[string]string", actualVal.Type()) } }) } func TestEnumUnmarshal(t *testing.T) { actual := calc.EnumDispenser_RandomStringLikeEnum() if actual != calc.StringEnum_B { t.Errorf("Expected StringEnum.B. Actual: %s", actual) } } func TestEnumRoundtrip(t *testing.T) { allTypes := calc.NewAllTypes() actual := allTypes.EnumMethod(calc.StringEnum_A) if actual != calc.StringEnum_A { t.Errorf("Expected StringEnum.A. Actual: %s", actual) } actual = allTypes.EnumMethod(calc.StringEnum_C) if actual != calc.StringEnum_C { t.Errorf("Expected StringEnum.C. Actual: %s", actual) } } func TestOptionalEnums(t *testing.T) { allTypes := calc.NewAllTypes() actual := allTypes.OptionalEnumValue() if actual != "" { t.Error("Expected value to be nil") } allTypes.SetOptionalEnumValue(calc.StringEnum_B) actual = allTypes.OptionalEnumValue() if actual != calc.StringEnum_B { t.Errorf("Expected StringEnum.B. Actual: %s", actual) } allTypes.SetOptionalEnumValue("") actual = allTypes.OptionalEnumValue() if actual != "" { t.Error("Expected value to be nil") } } func TestStructWithEnum(t *testing.T) { obj := calc.NewTestStructWithEnum() if !*obj.IsStringEnumA(&calc.StructWithEnum{Foo: calc.StringEnum_A}) { t.Error("Failed") } if !*obj.IsStringEnumB(&calc.StructWithEnum{ Foo: calc.StringEnum_B, Bar: calc.AllTypesEnum_THIS_IS_GREAT, }) { t.Error("Failed") } ret1 := obj.StructWithFoo() if ret1.Foo != calc.StringEnum_A { t.Error("Expecting Foo to be A") } if ret1.Bar != "" { t.Error("Expecting Bar to be nil") } ret2 := obj.StructWithFooBar() if ret2.Foo != calc.StringEnum_C { t.Error("Expecting Foo to be C") } if ret2.Bar != calc.AllTypesEnum_MY_ENUM_VALUE { t.Error("Expecting Foo to be MY_ENUM_VALUE") } } func TestReturnsSpecialParam(t *testing.T) { retSpecialParam := returnsParam.NewReturnsSpecialParameter() val := *retSpecialParam.ReturnsSpecialParam() expected := reflect.TypeOf(param.SpecialParameter{}) actual := reflect.TypeOf(val) if actual != expected { t.Errorf("Expected type: %s; Actual: %s", expected, actual) } }
242
jsii
aws
Go
package tests import ( "github.com/aws/jsii-runtime-go" "github.com/aws/jsii/jsii-calc/go/scopejsiicalclib" ) type pureNativeFriendlyRandom struct { _nextNumber float64 } func newPureNativeFriendlyRandom() *pureNativeFriendlyRandom { return &pureNativeFriendlyRandom{ _nextNumber: 1000, } } func (p *pureNativeFriendlyRandom) Next() *float64 { n := p._nextNumber p._nextNumber += 1000 return &n } func (p *pureNativeFriendlyRandom) Hello() *string { return jsii.String("I am a native!") } type subclassNativeFriendlyRandom struct { scopejsiicalclib.Number nextNumber float64 } func NewSubclassNativeFriendlyRandom() *subclassNativeFriendlyRandom { s := subclassNativeFriendlyRandom{nextNumber: 100} scopejsiicalclib.NewNumber_Override(&s, jsii.Number(908)) return &s } func (s *subclassNativeFriendlyRandom) Next() *float64 { defer func() { s.nextNumber += 100 }() return jsii.Number(s.nextNumber) } func (s *subclassNativeFriendlyRandom) Hello() *string { return jsii.String("SubclassNativeFriendlyRandom") }
47
jsii
aws
Go
package tests import ( "fmt" "testing" "github.com/aws/jsii-runtime-go" "github.com/aws/jsii/jsii-calc/go/jsiicalc/v3" "github.com/aws/jsii/jsii-calc/go/jsiicalc/v3/anonymous" ) func TestConstructor(t *testing.T) { defer expectPanic(t, "parameter unionProperty[0][\"bad\"] must be one of the allowed types: *StructA, *StructB; received \"Not a StructA or StructB\" (a string)") jsiicalc.NewClassWithCollectionOfUnions(&[]*map[string]interface{}{ { "good": jsiicalc.StructA{ RequiredString: jsii.String("present"), }, "bad": "Not a StructA or StructB", }, }) } func TestSetter(t *testing.T) { subject := jsiicalc.NewClassWithCollectionOfUnions(&[]*map[string]interface{}{}) defer expectPanic(t, "parameter val[0][\"bad\"] must be one of the allowed types: *StructA, *StructB; received \"Not a StructA or StructB\" (a string)") subject.SetUnionProperty(&[]*map[string]interface{}{ { "good": jsiicalc.StructA{ RequiredString: jsii.String("present"), }, "bad": "Not a StructA or StructB", }, }) } func TestStaticMethod(t *testing.T) { defer expectPanic(t, "parameter struct_ must be one of the allowed types: *StructA, *StructB; received \"Not a StructA\" (a string)") jsiicalc.StructUnionConsumer_IsStructA("Not a StructA") } func TestAnonymousObjectIsValid(t *testing.T) { strct := jsiicalc.StructUnionConsumer_ProvideStruct(jsii.String("A")) if !*jsiicalc.StructUnionConsumer_IsStructA(strct) { t.Error("Expected strct to be a StructA") } iface := anonymous.UseOptions_Provide(jsii.String("A")) if *anonymous.UseOptions_Consume(iface) != "A" { t.Error("Expected iface to produce A") } } func TestNestedUnion(t *testing.T) { func() { defer expectPanic(t, "parameter unionProperty[0] must be one of the allowed types: *map[string]interface{}, *[]interface{}; received 1337.42 (a float64)") jsiicalc.NewClassWithNestedUnion(&[]interface{}{1337.42}) }() func() { defer expectPanic(t, "parameter unionProperty[0][1] must be one of the allowed types: *StructA, *StructB; received 1337.42 (a float64)") jsiicalc.NewClassWithNestedUnion(&[]interface{}{ []interface{}{ jsiicalc.StructA{RequiredString: jsii.String("present")}, 1337.42, }, }) }() func() { defer expectPanic(t, "parameter unionProperty[0][\"bad\"] must be one of the allowed types: *StructA, *StructB; received \"Not a StructA or StructB\" (a string)") jsiicalc.NewClassWithNestedUnion(&[]interface{}{ map[string]interface{}{ "good": jsiicalc.StructA{RequiredString: jsii.String("present")}, "bad": "Not a StructA or StructB", }, }) }() } func TestVariadic(t *testing.T) { func() { defer expectPanic(t, "parameter union[1] must be one of the allowed types: *StructA, *StructB; received 1337.42 (a float64)") jsiicalc.NewVariadicTypeUnion(jsiicalc.StructA{RequiredString: jsii.String("present")}, 1337.42) }() // Should not raise jsiicalc.NewVariadicTypeUnion() } func expectPanic(t *testing.T, expected string) { if err := recover(); err != nil { actual := fmt.Sprintf("%v", err) if actual != expected { t.Errorf("Failed with error:\n%#v\nexpected to receive:\n%#v", actual, expected) } } else { t.Errorf("Expected test to fail with error:\n%#v", expected) } }
102
jsii
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/goimports" )
15
jsii
aws
Go
package addTen import ( "github.com/aws/jsii-runtime-go" calc "github.com/aws/jsii/jsii-calc/go/jsiicalc/v3" "github.com/aws/jsii/jsii-calc/go/scopejsiicalclib" ) func New(val *float64) calc.Add { return calc.NewAdd(scopejsiicalclib.NewNumber(val), scopejsiicalclib.NewNumber(jsii.Number(10))) }
12
jsii
aws
Go
package bellRinger import "github.com/aws/jsii/jsii-calc/go/jsiicalc/v3" func New() jsiicalc.IBellRinger { return &ringer{} } type ringer struct{} func (r *ringer) YourTurn(bell jsiicalc.IBell) { bell.Ring() }
14
jsii
aws
Go
package cdk16625 import ( "github.com/aws/jsii/jsii-calc/go/jsiicalc/v3" abc "github.com/aws/jsii/jsii-calc/go/jsiicalc/v3/cdk16625" ) func New() abc.Cdk16625 { c := &cdk16625{} abc.NewCdk16625_Override(c) return c } type cdk16625 struct { abc.Cdk16625 } func (c *cdk16625) Unwrap(rng jsiicalc.IRandomNumberGenerator) *float64 { return rng.Next() }
21
jsii
aws
Go
package doNotOverridePrivates import calc "github.com/aws/jsii/jsii-calc/go/jsiicalc/v3" type DoNotOverridePrivates struct { calc.DoNotOverridePrivates } func New() *DoNotOverridePrivates { d := &DoNotOverridePrivates{} calc.NewDoNotOverridePrivates_Override(d) return d } func (d *DoNotOverridePrivates) PrivateMethod() string { panic("This should not have been called!") } func (d *DoNotOverridePrivates) PrivateProperty() string { panic("This should not have been called!") } func (d *DoNotOverridePrivates) SetPrivateProperty(_ string) { panic("This should not have been called!") }
26
jsii
aws
Go
package friendlyRandom import ( "github.com/aws/jsii-runtime-go" "github.com/aws/jsii/jsii-calc/go/scopejsiicalclib" ) type SubclassFriendlyRandom struct { scopejsiicalclib.Number next float64 } func NewSubclass() *SubclassFriendlyRandom { s := &SubclassFriendlyRandom{next: 100} scopejsiicalclib.NewNumber_Override(s, jsii.Number(0)) return s } func (s *SubclassFriendlyRandom) Hello() *string { return jsii.String("SubclassNativeFriendlyRandom") } func (s *SubclassFriendlyRandom) Next() *float64 { defer func() { s.next += 100 }() return jsii.Number(s.next) } type PureFriendlyRandom struct { next float64 } func NewPure() *PureFriendlyRandom { return &PureFriendlyRandom{next: 1000} } func (p *PureFriendlyRandom) Hello() *string { return jsii.String("I am a native!") } func (p *PureFriendlyRandom) Next() *float64 { defer func() { p.next += 1000 }() return jsii.Number(p.next) }
44
jsii
aws
Go
package overrideAsyncMethods import ( "github.com/aws/jsii-runtime-go" "github.com/aws/jsii/jsii-calc/go/jsiicalc/v3" ) type OverrideAsyncMethods struct { jsiicalc.AsyncVirtualMethods } func New() *OverrideAsyncMethods { o := &OverrideAsyncMethods{} jsiicalc.NewAsyncVirtualMethods_Override(o) return o } func (o *OverrideAsyncMethods) OverrideMe(*float64) *float64 { return jsii.Number(*o.Foo() * 2) } func (o *OverrideAsyncMethods) Foo() *float64 { return jsii.Number(222) } type OverrideAsyncMethodsByBaseClass struct { OverrideAsyncMethods } func NewOverrideAsyncMethodsByBaseClass() *OverrideAsyncMethodsByBaseClass { o := &OverrideAsyncMethodsByBaseClass{} o.AsyncVirtualMethods = New() return o }
35
jsii
aws
Go
package syncOverrides import ( "github.com/aws/jsii-runtime-go" "github.com/aws/jsii/go-runtime-test/internal/overrideAsyncMethods" "github.com/aws/jsii/jsii-calc/go/jsiicalc/v3" ) type SyncOverrides struct { jsiicalc.SyncVirtualMethods AnotherTheProperty *string Multiplier int ReturnSuper bool CallAsync bool } func New() *SyncOverrides { s := &SyncOverrides{Multiplier: 1} jsiicalc.NewSyncVirtualMethods_Override(s) return s } func (t *SyncOverrides) VirtualMethod(n *float64) *float64 { if t.ReturnSuper { return t.SyncVirtualMethods.VirtualMethod(n) } if t.CallAsync { obj := overrideAsyncMethods.New() return obj.CallMe() } return jsii.Number(5 * (*n) * float64(t.Multiplier)) } func (t *SyncOverrides) TheProperty() *string { return jsii.String("I am an override!") } func (t *SyncOverrides) SetTheProperty(value *string) { t.AnotherTheProperty = value }
41
jsii
aws
Go
package twoOverrides import ( "github.com/aws/jsii-runtime-go" "github.com/aws/jsii/jsii-calc/go/jsiicalc/v3" ) type TwoOverrides struct { jsiicalc.AsyncVirtualMethods } func New() *TwoOverrides { t := &TwoOverrides{} jsiicalc.NewAsyncVirtualMethods_Override(t) return t } func (t *TwoOverrides) OverrideMe(*float64) *float64 { return jsii.Number(666) } func (t *TwoOverrides) OverrideMeToo() *float64 { return jsii.Number(10) }
25
jsii
aws
Go
package wallClock import ( "github.com/aws/jsii-runtime-go" "github.com/aws/jsii/jsii-calc/go/jsiicalc/v3" ) type WallClock struct { nowAsISO string } func NewWallClock(nowAsISO string) *WallClock { return &WallClock{nowAsISO} } func (w *WallClock) Iso8601Now() *string { return jsii.String(w.nowAsISO) } type Entropy struct { jsiicalc.Entropy } func NewEntropy(clock jsiicalc.IWallClock) *Entropy { e := &Entropy{} jsiicalc.NewEntropy_Override(e, clock) return e } func (e *Entropy) Repeat(word *string) *string { return word }
33
jsii
aws
Go
func foo(x *string, y *string, z *string) { if y == nil { y = jsii.String("hello") } fmt.Println(*x, *y, *z) }
7
jsii
aws
Go
type struct_ struct { x *string y *string } func foo(s *struct_) { fmt.Println(*s.x, *s.y) }
8
jsii
aws
Go
callSomeFunction(jsii.Number(1), jsii.Number(2), jsii.Number(3))
2
jsii
aws
Go
foo(map[string][]map[string]*f64{ "list": []map[string]*f64{ map[string]*f64{ "a": jsii.Number(1), "b": jsii.Number(2), }, map[string]*f64{ "a": jsii.Number(3), "b": jsii.Number(4), }, }, })
13
jsii
aws
Go
func foo(xs map[string]*string) { } foo(map[string]*string{ "foo": jsii.String("bar"), "schmoo": jsii.String("schmar"), })
8
jsii
aws
Go
someObject.callSomeFunction(jsii.Number(1), jsii.Number(2), jsii.Number(3))
2
jsii
aws
Go
this.callSomeFunction(jsii.Number(25))
2
jsii
aws
Go
foo := "hello" callFunction(map[string]*string{ "foo": jsii.String(foo), })
5
jsii
aws
Go
someObject_CallSomeFunction(jsii.Number(1), jsii.Number(2), jsii.Number(3))
2
jsii
aws
Go
callSomeFunction(this, jsii.Number(25))
2
jsii
aws
Go
foo(jsii.Number(25), map[string]interface{}{ "foo": jsii.Number(3), "banana": jsii.String("hello"), })
5
jsii
aws
Go
foo(jsii.Number(25), map[string]interface{}{ "foo": jsii.Number(3), "deeper": map[string]*f64{ "a": jsii.Number(1), "b": jsii.Number(2), }, })
8
jsii
aws
Go
foo(jsii.Number(25), map[string]interface{}{ "foo": jsii.Number(3), "deeper": map[string]*f64{ "a": jsii.Number(1), "b": jsii.Number(2), }, })
8
jsii
aws
Go
foo(jsii.Number(25), map[string]interface{}{ "foo": jsii.Number(3), "banana": jsii.String("hello"), })
6
jsii
aws
Go
foo(jsii.Number(25), map[string]interface{}{ "foo": jsii.Number(3), "banana": jsii.String("hello"), })
5
jsii
aws
Go
type baseDeeperStruct struct { a *f64 } type deeperStruct struct { baseDeeperStruct b *f64 } type outerStruct struct { foo *f64 deeper *deeperStruct } func foo(x *f64, outer *outerStruct) { } foo(jsii.Number(25), &outerStruct{ Foo: jsii.Number(3), Deeper: &deeperStruct{ A: jsii.Number(1), B: jsii.Number(2), }, })
25
jsii
aws
Go
type myClass struct { x *string } func newMyClass(y *string) *myClass { this := &myClass{} this.x = y return this }
10
jsii
aws
Go
type myClass struct { x *string } func newMyClass(y *string) *myClass { this := &myClass{} this.x = y return this }
10
jsii
aws
Go
type myClass struct { } func (this *myClass) resolve() interface{} { return jsii.Number(42) }
7
jsii
aws
Go
type otherName struct { } func newOtherName() *otherName { this := &otherName{} return this }
8
jsii
aws
Go
type myClass struct { SomeOtherClass }
4