pulumi/pkg/codegen/hcl2
Abhinav Gupta 9b43e56add
pkg/hcl2/model: Make String methods thread-safe
ObjectType.String and a few other types
do a fair bit of computation to build a string representation.
They memoize the result in an internal `s` field.
This causes a data race if two goroutines call `String()`
on the same object at the same time.

Tests in pkg/codegen/pcl ran into the following
from ObjectType.String.

```
WARNING: DATA RACE
Write at 0x00c00055c030 by goroutine 36:
  github.com/pulumi/pulumi/pkg/v3/codegen/hcl2/model.(*ObjectType).string()
      [..]/pulumi/pkg/codegen/hcl2/model/type_object.go:300 +0x418
  [.. snip ..]
  github.com/pulumi/pulumi/pkg/v3/codegen/pcl.TestApplyRewriter.func1()
      [..]/pulumi/pkg/codegen/pcl/rewrite_apply_test.go:176 +0x68
  testing.tRunner()
      /opt/homebrew/Cellar/go/1.19.5/libexec/src/testing/testing.go:1446 +0x188
  testing.(*T).Run.func1()
      /opt/homebrew/Cellar/go/1.19.5/libexec/src/testing/testing.go:1493 +0x40

Previous read at 0x00c00055c030 by goroutine 37:
  github.com/pulumi/pulumi/pkg/v3/codegen/hcl2/model.(*ObjectType).string()
      [..]/pulumi/pkg/codegen/hcl2/model/type_object.go:276 +0x40
  github.com/pulumi/pulumi/pkg/v3/codegen/hcl2/model.(*OutputType).string()
      [..]/pulumi/pkg/codegen/hcl2/model/type_output.go:110 +0x4c
  [..]
```

To fix this, turn the memoized field into an `atomic.Value`
in all types that memoize it.

When two goroutines race to calculate this value,
one of them will do extra work that will be thrown away,
but it won't cause a data race.

Refs #10092
2023-01-18 16:18:17 -08:00
..
model pkg/hcl2/model: Make String methods thread-safe 2023-01-18 16:18:17 -08:00
syntax gosimple: Simplify loops 2023-01-12 09:55:34 -08:00