Compare commits

...
Author SHA1 Message Date
lars.jurgensen ddf18216be chore(OCISDEV-900): revert graphAPI markProcessing change 2026-08-24 15:18:48 +02:00
lars.jurgensen 04eefa1e6f chore(OCISDEV-900): bump reva version 2026-08-24 11:14:08 +02:00
lars.jurgensen bd374e47ff fix(OCISDEV-900): set upload_directory to StorageRoot/uploads in OCM revaconfig
Service-level upload_directory is used as-is by reva (no /uploads join).
Pass StorageRoot + "/uploads" explicitly so rootless-driver pattern is clear.
2026-08-19 17:19:54 +02:00
lars.jurgensen a5c539b9bb chore(OCISDEV-900): bump golang.org/x/mod to v0.40.0 (CVE-2026-56864/56865) 2026-08-19 16:58:16 +02:00
lars.jurgensen 98a353424c chore(OCISDEV-900): pin transitive deps to master versions after reva bump
Prevent unnecessary downgrades introduced by reva b1626ed21a.
Only intentional diff vs master: reva bump + ceph/go-ceph v0.41.0 (required by new reva).
2026-08-19 16:46:35 +02:00
lars.jurgensen 876a0ef418 refactor(OCISDEV-900): rebase onto master, bump reva to b1626ed21a
- Remove markprocessing opaque from TouchFile in personaldata.go
- Add upload_directory to OCM dataprovider and storageprovider revaconfig
- Add mount_id to storage-users dataprovider revaconfig
- Bump reva/v2 to b1626ed21a (feat: handle missing node id in tus)
2026-08-19 16:22:42 +02:00
56 changed files with 2774 additions and 2126 deletions

No files matched your search

+4 -4
View File
@@ -67,7 +67,7 @@ require (
github.com/open-policy-agent/opa v1.19.0
github.com/orcaman/concurrent-map v1.0.0
github.com/owncloud/libre-graph-api-go v1.0.5-0.20260216101009-eeac018af245
github.com/owncloud/reva/v2 v2.0.0-20260813121157-d386075a0421
github.com/owncloud/reva/v2 v2.0.0-20260821144357-79bb0520701d
github.com/pkg/errors v0.9.1
github.com/pkg/xattr v0.4.12
github.com/prometheus/client_golang v1.24.1
@@ -155,7 +155,7 @@ require (
github.com/blevesearch/zapx/v17 v17.1.2 // indirect
github.com/bluele/gcache v0.0.2 // indirect
github.com/bombsimon/logrusr/v3 v3.1.0 // indirect
github.com/ceph/go-ceph v0.40.0 // indirect
github.com/ceph/go-ceph v0.41.0 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/cevaris/ordered_map v0.0.0-20190319150403-3adeae072e73 // indirect
github.com/clipperhouse/displaywidth v0.11.0 // indirect
@@ -340,10 +340,10 @@ require (
go.uber.org/zap v1.27.1 // indirect
go.yaml.in/yaml/v2 v2.4.4 // indirect
go.yaml.in/yaml/v3 v3.0.5 // indirect
golang.org/x/mod v0.38.0 // indirect
golang.org/x/mod v0.40.0 // indirect
golang.org/x/sys v0.47.0 // indirect
golang.org/x/time v0.15.0 // indirect
golang.org/x/tools v0.48.0 // indirect
golang.org/x/tools v0.49.0 // indirect
google.golang.org/genproto v0.0.0-20260319201613-d00831a3d3e7 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20260803160001-6ac0973c030d // indirect
gopkg.in/cenkalti/backoff.v1 v1.1.0 // indirect
+10 -10
View File
@@ -167,8 +167,8 @@ github.com/cenkalti/backoff v2.2.1+incompatible/go.mod h1:90ReRw6GdpyfrHakVjL/QH
github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM=
github.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw=
github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU=
github.com/ceph/go-ceph v0.40.0 h1:Wz9WOX6i73Hz74mpwhTO9S6IyX3eFPv88VUc7FRMPRk=
github.com/ceph/go-ceph v0.40.0/go.mod h1:1oFtT/x/4y+teLsNiogdd/Kj81Gmrw6JM5w1bWnZoc4=
github.com/ceph/go-ceph v0.41.0 h1:uATh5+zR1KWOQCoBYj4uEfuAPsSccajOGXWW8u8UTgA=
github.com/ceph/go-ceph v0.41.0/go.mod h1:8tvljRxQ65aEtRt7aCxzuPpN7tiwPHCPPSuAqQ5teCY=
github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/cespare/xxhash/v2 v2.1.2/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
@@ -393,8 +393,8 @@ github.com/gofrs/flock v0.13.0 h1:95JolYOvGMqeH31+FC7D2+uULf6mG61mEZ/A8dRYMzw=
github.com/gofrs/flock v0.13.0/go.mod h1:jxeyy9R1auM5S6JYDBhDt+E2TCo7DkratH4Pgi8P+Z0=
github.com/gofrs/uuid v4.4.0+incompatible h1:3qXRTX8/NbyulANqlc0lchS1gqAVxRgsuW1YrTJupqA=
github.com/gofrs/uuid v4.4.0+incompatible/go.mod h1:b2aQJv3Z4Fp6yNu3cdSllBxTCLRxnplIgP/c0N/04lM=
github.com/gofrs/uuid/v5 v5.4.0 h1:EfbpCTjqMuGyq5ZJwxqzn3Cbr2d0rUZU7v5ycAk/e/0=
github.com/gofrs/uuid/v5 v5.4.0/go.mod h1:CDOjlDMVAtN56jqyRUZh58JT31Tiw7/oQyEXZV+9bD8=
github.com/gofrs/uuid/v5 v5.5.0 h1:FkPv6jYQRbZtH3bD8yC7106u+CedTCLF8+t7CLHSZNo=
github.com/gofrs/uuid/v5 v5.5.0/go.mod h1:bbAA98EoIlxyRHIVg6ektCSsZ5n8mSbwgEhvhMYlZgg=
github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ=
github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q=
github.com/golang-jwt/jwt/v4 v4.5.2 h1:YtQM7lnr8iZ+j5q71MGKkNw9Mn7AjHM68uc9g5fXeUI=
@@ -736,8 +736,8 @@ github.com/orcaman/concurrent-map v1.0.0 h1:I/2A2XPCb4IuQWcQhBhSwGfiuybl/J0ev9HD
github.com/orcaman/concurrent-map v1.0.0/go.mod h1:Lu3tH6HLW3feq74c2GC+jIMS/K2CFcDWnWD9XkenwhI=
github.com/owncloud/libre-graph-api-go v1.0.5-0.20260216101009-eeac018af245 h1:JRidLTAKhnvyLMRtVtSF4lhBa0NSAOs6fof+d6JnKII=
github.com/owncloud/libre-graph-api-go v1.0.5-0.20260216101009-eeac018af245/go.mod h1:z61VMGAJRtR1nbgXWiNoCkxUXP1B3Je9rMuJbnGd+Og=
github.com/owncloud/reva/v2 v2.0.0-20260813121157-d386075a0421 h1:orjzG6JMpulTJvkeg//KwgeqdrOMGXAO0K6GaH4XCxI=
github.com/owncloud/reva/v2 v2.0.0-20260813121157-d386075a0421/go.mod h1:f4ymc4PUG6a3QSOHXq7Q9Ck5udiSNU6Lv2Im2Q0jvRc=
github.com/owncloud/reva/v2 v2.0.0-20260821144357-79bb0520701d h1:aXW5V1zEJnBZTciBDug02m1eEMkA/mHKer1PiBSoHOk=
github.com/owncloud/reva/v2 v2.0.0-20260821144357-79bb0520701d/go.mod h1:DGoRFcaZdpikfpo14QD9gPHUDw6oodKdFOrVLSa1raA=
github.com/oxtoacart/bpool v0.0.0-20190530202638-03653db5a59c h1:rp5dCmg/yLR3mgFuSOe4oEnDDmGLROTvMragMUXpTQw=
github.com/oxtoacart/bpool v0.0.0-20190530202638-03653db5a59c/go.mod h1:X07ZCGwUbLaax7L0S3Tw4hpejzu63ZrrQiUe6W0hcy0=
github.com/pablodz/inotifywaitgo v0.0.12 h1:DVJJTFMDlSAdO46yisPF2vzozs/r+4k6ih8MVghq78M=
@@ -1054,8 +1054,8 @@ golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/mod v0.38.0 h1:MECBjubtXD7yj4HrhIUcywNaGeNVUdfVnxmPajOk4yk=
golang.org/x/mod v0.38.0/go.mod h1:V6Xz0pq8TQ3dGqVQ1FVHuelZpAL0uNhSkk9ogYP3c40=
golang.org/x/mod v0.40.0 h1:hUv+3cXcdRHz08UmSiOob7sadHig73uo5bkXxQ/tvUs=
golang.org/x/mod v0.40.0/go.mod h1:0/weTWkPWGBikyTWAX3dkjVztMmBA5hM0DH6BElSupE=
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
@@ -1264,8 +1264,8 @@ golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4f
golang.org/x/tools v0.0.0-20210112230658-8b4aab62c064/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
golang.org/x/tools v0.48.0 h1:3+hClM1aLL5mjMKm5ovokw9epgRXPuu2tILgismM6RE=
golang.org/x/tools v0.48.0/go.mod h1:08xX0orndb/F7jJxGDicx061tyd5pcMto75YMAXr6lk=
golang.org/x/tools v0.49.0 h1:3NI7VXzL9+1WZD52Dx2ttoPwD5DWrFGpl9mFZDlmisI=
golang.org/x/tools v0.49.0/go.mod h1:SJNXV9DBKT0UbdttsQjbfJlAE/q+y36++zo3uL3N0Oo=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
+6 -3
View File
@@ -3,6 +3,7 @@ package revaconfig
import (
"math"
"net/url"
"path/filepath"
"github.com/owncloud/ocis/v2/ocis-pkg/log"
"github.com/owncloud/ocis/v2/services/ocm/pkg/config"
@@ -91,8 +92,9 @@ func OCMConfigFromStruct(cfg *config.Config, logger log.Logger) map[string]inter
"service_account_secret": cfg.ServiceAccount.Secret,
},
"dataprovider": map[string]interface{}{
"prefix": "data",
"driver": "ocmreceived",
"prefix": "data",
"driver": "ocmreceived",
"upload_directory": filepath.Join(cfg.OCMStorageProvider.StorageRoot, "uploads"),
"drivers": map[string]interface{}{
"ocmreceived": map[string]interface{}{
"insecure": cfg.OCMStorageProvider.Insecure,
@@ -181,7 +183,8 @@ func OCMConfigFromStruct(cfg *config.Config, logger log.Logger) map[string]inter
},
},
"storageprovider": map[string]interface{}{
"driver": "ocmreceived",
"driver": "ocmreceived",
"upload_directory": filepath.Join(cfg.OCMStorageProvider.StorageRoot, "uploads"),
"drivers": map[string]interface{}{
"ocmreceived": map[string]interface{}{
"insecure": cfg.OCMStorageProvider.Insecure,
@@ -80,6 +80,7 @@ func StorageUsersConfigFromStruct(cfg *config.Config) map[string]interface{} {
"prefix": cfg.HTTP.Prefix,
"driver": cfg.Driver,
"drivers": DataProviderDrivers(cfg),
"mount_id": cfg.MountID,
"nats_address": cfg.Events.Addr,
"nats_clusterID": cfg.Events.ClusterID,
"nats_tls_insecure": cfg.Events.TLSInsecure,
+1 -1
View File
@@ -24,7 +24,7 @@ func (fsa *FSAdmin) PinSubVolume(volume, subvolume, pintype, pinsetting string)
return parsePathResponse(fsa.marshalMgrCommand(m))
}
// PinSubVolumeGroup pins subvolume to ranks according to policies. A valid pin
// PinSubVolumeGroup pins subvolume group to ranks according to policies. A valid pin
// setting value depends on the type of pin as described in the docs from
// https://docs.ceph.com/en/latest/cephfs/multimds/#cephfs-pinning and
// https://docs.ceph.com/en/latest/cephfs/multimds/#setting-subtree-partitioning-policies
+28
View File
@@ -0,0 +1,28 @@
//go:build !nautilus && ceph_preview
package admin
// PinSubVolumeInGroup pins a subvolume in a volume and optional subvolume group
// to ranks according to policies. A valid pin setting value depends on the type
// of pin as described in the docs from
// https://docs.ceph.com/en/latest/cephfs/multimds/#cephfs-pinning and
// https://docs.ceph.com/en/latest/cephfs/multimds/#setting-subtree-partitioning-policies
//
// Similar To:
//
// ceph fs subvolume pin <vol_name> <sub_name> <pin_type> <pin_setting> [--group_name=<group>]
func (fsa *FSAdmin) PinSubVolumeInGroup(volume, group, subvolume, pintype, pinsetting string) (string, error) {
m := map[string]string{
"prefix": "fs subvolume pin",
"format": "json",
"vol_name": volume,
"sub_name": subvolume,
"pin_type": pintype,
"pin_setting": pinsetting,
}
if group != NoGroup {
m["group_name"] = group
}
return parsePathResponse(fsa.marshalMgrCommand(m))
}
@@ -47,6 +47,7 @@ import (
"github.com/owncloud/reva/v2/pkg/storage"
"github.com/owncloud/reva/v2/pkg/storage/fs/registry"
"github.com/owncloud/reva/v2/pkg/storagespace"
"github.com/owncloud/reva/v2/pkg/upload"
"github.com/owncloud/reva/v2/pkg/utils"
"github.com/pkg/errors"
"github.com/rs/zerolog"
@@ -71,6 +72,7 @@ type config struct {
MountID string `mapstructure:"mount_id"`
UploadExpiration int64 `mapstructure:"upload_expiration" docs:"0;Duration for how long uploads will be valid."`
Events eventconfig `mapstructure:"events" docs:"0;Event stream configuration"`
UploadDirectory string `mapstructure:"upload_directory" docs:";Local directory for staging upload sessions. Overrides the driver's root. Required for drivers that have no local filesystem root."`
}
type eventconfig struct {
@@ -106,6 +108,7 @@ func (c *config) init() {
type Service struct {
conf *config
Storage storage.FS
Coordinator upload.Coordinator
dataServerURL *url.URL
availableXS []*provider.ResourceChecksumPriority
}
@@ -175,7 +178,14 @@ func New(m map[string]interface{}, ss *grpc.Server, log *zerolog.Logger) (rgrpc.
c.init()
fs, err := getFS(c, log)
// One stream for both the driver and the coordinator: a second one would open a
// second nats connection for the same events.
evstream, err := estreamFromConfig(c.Events)
if err != nil {
return nil, err
}
fs, err := getFS(c, evstream, log)
if err != nil {
return nil, err
}
@@ -202,9 +212,16 @@ func New(m map[string]interface{}, ss *grpc.Server, log *zerolog.Logger) (rgrpc.
return nil, err
}
// storageprovider only initiates uploads; the data path assembles chunks, so no chunking here.
coord, err := upload.NewCoordinatorFromConfig(c.UploadDirectory, c.Drivers[c.Driver], fs, evstream, log, false)
if err != nil {
return nil, fmt.Errorf("storageprovider: %w", err)
}
service := &Service{
conf: c,
Storage: fs,
Coordinator: coord,
dataServerURL: u,
availableXS: xsTypes,
}
@@ -427,7 +444,7 @@ func (s *Service) InitiateFileUpload(ctx context.Context, req *provider.Initiate
metadata["expires"] = strconv.Itoa(int(expirationTimestamp.Seconds))
}
uploadIDs, err := s.Storage.InitiateUpload(ctx, req.Ref, uploadLength, metadata)
uploadIDs, err := s.Coordinator.InitiateUpload(ctx, req.Ref, uploadLength, metadata)
if err != nil {
var st *rpc.Status
switch err.(type) {
@@ -1266,12 +1283,7 @@ func (s *Service) addMissingStorageProviderID(resourceID *provider.ResourceId, s
}
}
func getFS(c *config, log *zerolog.Logger) (storage.FS, error) {
evstream, err := estreamFromConfig(c.Events)
if err != nil {
return nil, err
}
func getFS(c *config, evstream events.Stream, log *zerolog.Logger) (storage.FS, error) {
if f, ok := registry.NewFuncs[c.Driver]; ok {
driverConf := c.Drivers[c.Driver]
driverConf["mount_id"] = c.MountID // pass the mount id to the driver
@@ -33,6 +33,7 @@ import (
"github.com/owncloud/reva/v2/pkg/rhttp/router"
"github.com/owncloud/reva/v2/pkg/storage"
"github.com/owncloud/reva/v2/pkg/storage/fs/registry"
"github.com/owncloud/reva/v2/pkg/upload"
)
func init() {
@@ -51,6 +52,7 @@ type config struct {
NatsEnableTLS bool `mapstructure:"nats_enable_tls"`
NatsUsername string `mapstructure:"nats_username"`
NatsPassword string `mapstructure:"nats_password"`
UploadDirectory string `mapstructure:"upload_directory" docs:";Local directory for staging upload sessions. Overrides the driver's root. Required for drivers that have no local filesystem root."`
}
func (c *config) init() {
@@ -104,7 +106,21 @@ func New(m map[string]interface{}, log *zerolog.Logger) (global.Service, error)
return nil, err
}
dataTXs, err := getDataTXs(conf, fs, evstream, log)
// the data path assembles chunks, so enable chunking
coord, err := upload.NewCoordinatorFromConfig(conf.UploadDirectory, conf.Drivers[conf.Driver], fs, evstream, log, true)
if err != nil {
return nil, fmt.Errorf("dataprovider: %w", err)
}
// only the data path consumes postprocessing results: one consumer group gets
// one copy of each event, so a second subscriber would take half of them
if ac := upload.AsyncConfFromDriverConf(conf.Drivers[conf.Driver]); ac.Enabled {
if err := coord.StartPostprocessing(evstream, ac.ConsumerGroup, ac.MountID, ac.NumConsumers); err != nil {
return nil, fmt.Errorf("dataprovider: could not start postprocessing: %w", err)
}
}
dataTXs, err := getDataTXs(conf, coord, fs, evstream, log)
if err != nil {
return nil, err
}
@@ -126,7 +142,7 @@ func getFS(c *config, stream events.Stream, log *zerolog.Logger) (storage.FS, er
return nil, fmt.Errorf("driver not found: %s", c.Driver)
}
func getDataTXs(c *config, fs storage.FS, publisher events.Publisher, log *zerolog.Logger) (map[string]http.Handler, error) {
func getDataTXs(c *config, coord upload.Coordinator, fs storage.FS, publisher events.Publisher, log *zerolog.Logger) (map[string]http.Handler, error) {
if c.DataTXs == nil {
c.DataTXs = make(map[string]map[string]interface{})
}
@@ -146,7 +162,7 @@ func getDataTXs(c *config, fs storage.FS, publisher events.Publisher, log *zerol
for t := range c.DataTXs {
if f, ok := datatxregistry.NewFuncs[t]; ok {
if tx, err := f(c.DataTXs[t], publisher, log); err == nil {
if handler, err := tx.Handler(fs); err == nil {
if handler, err := tx.Handler(coord, fs); err == nil {
txs[t] = handler
}
}
@@ -319,7 +319,8 @@ func (s *svc) handleTusPost(ctx context.Context, w http.ResponseWriter, r *http.
sReq.Ref.Path = uReq.Ref.GetPath()
sReq.Ref.ResourceId = nil
} else {
if resid, err := storagespace.ParseID(httpRes.Header.Get(net.HeaderOCFileID)); err == nil {
// new files have no node id yet; keep the path-based ref instead
if resid, err := storagespace.ParseID(httpRes.Header.Get(net.HeaderOCFileID)); err == nil && resid.GetOpaqueId() != "" {
sReq.Ref = &provider.Reference{
ResourceId: &resid,
}
+1 -1
View File
@@ -716,6 +716,6 @@ func (d *driver) PrepareUpload(_ context.Context, _ *provider.Reference, _ strin
return &storage.PrepareUploadResult{VersionCreated: info.NodeExisted}, nil
}
func (d *driver) RollbackUpload(_ context.Context, _ *provider.Reference, _ string, _ bool, _ int64) error {
func (d *driver) RollbackUpload(_ context.Context, _ *provider.Reference, _ string, _ storage.RollbackInfo) error {
return nil
}
+4 -1
View File
@@ -28,12 +28,15 @@ import (
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
"github.com/owncloud/reva/v2/pkg/events"
"github.com/owncloud/reva/v2/pkg/storage"
"github.com/owncloud/reva/v2/pkg/upload"
"github.com/owncloud/reva/v2/pkg/utils"
)
// DataTX provides an abstraction around various data transfer protocols.
type DataTX interface {
Handler(fs storage.FS) (http.Handler, error)
// Handler serves the protocol's data path. Uploads go through coord, which
// owns the upload lifecycle for every driver; downloads read from driver.
Handler(coord upload.Coordinator, driver storage.FS) (http.Handler, error)
}
// EmitFileUploadedEvent is a helper function which publishes a FileUploaded event
@@ -24,8 +24,8 @@ import (
userpb "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1"
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
ctxpkg "github.com/owncloud/reva/v2/pkg/ctx"
"github.com/mitchellh/mapstructure"
ctxpkg "github.com/owncloud/reva/v2/pkg/ctx"
"github.com/pkg/errors"
"github.com/rs/zerolog"
@@ -40,6 +40,7 @@ import (
"github.com/owncloud/reva/v2/pkg/storage"
"github.com/owncloud/reva/v2/pkg/storage/cache"
"github.com/owncloud/reva/v2/pkg/storagespace"
"github.com/owncloud/reva/v2/pkg/upload"
"github.com/owncloud/reva/v2/pkg/utils"
)
@@ -78,7 +79,7 @@ func New(m map[string]interface{}, publisher events.Publisher, log *zerolog.Logg
}, nil
}
func (m *manager) Handler(fs storage.FS) (http.Handler, error) {
func (m *manager) Handler(coord upload.Coordinator, driver storage.FS) (http.Handler, error) {
h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
sublog := m.log.With().Str("path", r.URL.Path).Logger()
r = r.WithContext(appctx.WithLogger(r.Context(), &sublog))
@@ -92,7 +93,7 @@ func (m *manager) Handler(fs storage.FS) (http.Handler, error) {
metrics.DownloadsActive.Sub(1)
}()
}
download.GetOrHeadFile(w, r, fs, "")
download.GetOrHeadFile(w, r, driver, "")
case "PUT":
metrics.UploadsActive.Add(1)
defer func() {
@@ -114,7 +115,7 @@ func (m *manager) Handler(fs storage.FS) (http.Handler, error) {
ctx = ctxpkg.ContextSetLockID(ctx, lockID)
}
info, err := fs.Upload(ctx, storage.UploadRequest{
info, err := coord.Upload(ctx, storage.UploadRequest{
Ref: ref,
Body: r.Body,
Length: r.ContentLength,
@@ -42,6 +42,7 @@ import (
"github.com/owncloud/reva/v2/pkg/storage"
"github.com/owncloud/reva/v2/pkg/storage/cache"
"github.com/owncloud/reva/v2/pkg/storagespace"
"github.com/owncloud/reva/v2/pkg/upload"
"github.com/owncloud/reva/v2/pkg/utils"
)
@@ -80,7 +81,7 @@ func New(m map[string]interface{}, publisher events.Publisher, log *zerolog.Logg
}, nil
}
func (m *manager) Handler(fs storage.FS) (http.Handler, error) {
func (m *manager) Handler(coord upload.Coordinator, driver storage.FS) (http.Handler, error) {
h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var spaceID string
spaceID, r.URL.Path = router.ShiftPath(r.URL.Path)
@@ -97,7 +98,7 @@ func (m *manager) Handler(fs storage.FS) (http.Handler, error) {
metrics.DownloadsActive.Sub(1)
}()
}
download.GetOrHeadFile(w, r, fs, spaceID)
download.GetOrHeadFile(w, r, driver, spaceID)
case "PUT":
metrics.UploadsActive.Add(1)
defer func() {
@@ -117,7 +118,7 @@ func (m *manager) Handler(fs storage.FS) (http.Handler, error) {
Path: fn,
}
var info *provider.ResourceInfo
info, err = fs.Upload(ctx, storage.UploadRequest{
info, err = coord.Upload(ctx, storage.UploadRequest{
Ref: ref,
Body: r.Body,
Length: r.ContentLength,
+34 -45
View File
@@ -33,13 +33,13 @@ import (
"github.com/owncloud/reva/v2/internal/http/services/owncloud/ocdav/net"
"github.com/owncloud/reva/v2/pkg/appctx"
"github.com/owncloud/reva/v2/pkg/errtypes"
"github.com/owncloud/reva/v2/pkg/events"
"github.com/owncloud/reva/v2/pkg/rhttp/datatx"
"github.com/owncloud/reva/v2/pkg/rhttp/datatx/manager/registry"
"github.com/owncloud/reva/v2/pkg/rhttp/datatx/metrics"
"github.com/owncloud/reva/v2/pkg/storage"
"github.com/owncloud/reva/v2/pkg/storagespace"
"github.com/owncloud/reva/v2/pkg/upload"
)
func init() {
@@ -87,20 +87,14 @@ func New(m map[string]interface{}, publisher events.Publisher, log *zerolog.Logg
}, nil
}
func (m *manager) Handler(fs storage.FS) (http.Handler, error) {
composable, ok := fs.(storage.ComposableFS)
if !ok {
return nil, errtypes.NotSupported("file system does not support the tus protocol")
}
func (m *manager) Handler(coord upload.Coordinator, _ storage.FS) (http.Handler, error) {
// A storage backend for tusd may consist of multiple different parts which
// handle upload creation, locking, termination and so on. The composer is a
// place where all those separated pieces are joined together. In this example
// we only use the file store but you may plug in multiple.
// place where all those separated pieces are joined together.
composer := tusd.NewStoreComposer()
// let the composable storage tell tus which extensions it supports
composable.UseIn(composer)
// the coordinator serves the tus protocol on behalf of every driver
coord.UseIn(composer)
config := tusd.Config{
StoreComposer: composer,
@@ -130,33 +124,29 @@ func (m *manager) Handler(fs storage.FS) (http.Handler, error) {
return nil, err
}
if usl, ok := fs.(storage.UploadSessionLister); ok {
// We can currently only send updates if the fs is decomposedfs as we read very specific keys from the storage map of the tus info
go func() {
for {
ev := <-handler.CompleteUploads
// We should be able to get the upload progress with fs.GetUploadProgress, but currently tus will erase the info files
// so we create a Progress instance here that is used to read the correct properties
ups, err := usl.ListUploadSessions(context.Background(), storage.UploadSessionFilter{ID: &ev.Upload.ID})
if err != nil {
appctx.GetLogger(context.Background()).Error().Err(err).Str("session", ev.Upload.ID).Msg("failed to list upload session")
} else {
if len(ups) < 1 {
appctx.GetLogger(context.Background()).Error().Str("session", ev.Upload.ID).Msg("upload session not found")
continue
}
up := ups[0]
executant := up.Executant()
ref := up.Reference()
if m.publisher != nil {
if err := datatx.EmitFileUploadedEvent(up.SpaceOwner(), &executant, &ref, m.publisher); err != nil {
appctx.GetLogger(context.Background()).Error().Err(err).Msg("failed to publish FileUploaded event")
}
}
go func() {
for {
ev := <-handler.CompleteUploads
// tus erases its info files, so read the session back for the event's properties
ups, err := coord.ListUploadSessions(context.Background(), storage.UploadSessionFilter{ID: &ev.Upload.ID})
if err != nil {
appctx.GetLogger(context.Background()).Error().Err(err).Str("session", ev.Upload.ID).Msg("failed to list upload session")
continue
}
if len(ups) < 1 {
appctx.GetLogger(context.Background()).Error().Str("session", ev.Upload.ID).Msg("upload session not found")
continue
}
up := ups[0]
executant := up.Executant()
ref := up.Reference()
if m.publisher != nil {
if err := datatx.EmitFileUploadedEvent(up.SpaceOwner(), &executant, &ref, m.publisher); err != nil {
appctx.GetLogger(context.Background()).Error().Err(err).Msg("failed to publish FileUploaded event")
}
}
}()
}
}
}()
h := handler.Middleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
sublog := m.log.With().Str("uploadid", r.URL.Path).Logger()
@@ -174,7 +164,7 @@ func (m *manager) Handler(fs storage.FS) (http.Handler, error) {
metrics.UploadsActive.Sub(1)
}()
// set etag, mtime and file id
setHeaders(fs, w, r)
setHeaders(coord, w, r)
handler.PostFile(w, r)
case "HEAD":
handler.HeadFile(w, r)
@@ -184,7 +174,7 @@ func (m *manager) Handler(fs storage.FS) (http.Handler, error) {
metrics.UploadsActive.Sub(1)
}()
// set etag, mtime and file id
setHeaders(fs, w, r)
setHeaders(coord, w, r)
handler.PatchFile(w, r)
case "DELETE":
handler.DelFile(w, r)
@@ -205,15 +195,10 @@ func (m *manager) Handler(fs storage.FS) (http.Handler, error) {
return h, nil
}
func setHeaders(fs storage.FS, w http.ResponseWriter, r *http.Request) {
func setHeaders(coord upload.Coordinator, w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
id := path.Base(r.URL.Path)
datastore, ok := fs.(tusd.DataStore)
if !ok {
appctx.GetLogger(ctx).Error().Interface("fs", fs).Msg("storage is not a tus datastore")
return
}
upload, err := datastore.GetUpload(ctx, id)
upload, err := coord.GetUpload(ctx, id)
if err != nil {
appctx.GetLogger(ctx).Error().Err(err).Msg("could not get upload from storage")
return
@@ -227,6 +212,10 @@ func setHeaders(fs storage.FS, w http.ResponseWriter, r *http.Request) {
if expires != "" {
w.Header().Set(net.HeaderTusUploadExpires, expires)
}
// the node id is only valid once the upload commits; skip the header for new files
if info.Storage["NodeExists"] != "true" {
return
}
resourceid := &provider.ResourceId{
StorageId: info.MetaData["providerID"],
SpaceId: info.Storage["SpaceRoot"],
+1 -1
View File
@@ -159,7 +159,7 @@ func (fs *cephfs) PrepareUpload(_ context.Context, _ *provider.Reference, _ stri
return &storage.PrepareUploadResult{VersionCreated: info.NodeExisted}, nil
}
func (fs *cephfs) RollbackUpload(_ context.Context, _ *provider.Reference, _ string, _ bool, _ int64) error {
func (fs *cephfs) RollbackUpload(_ context.Context, _ *provider.Reference, _ string, _ storage.RollbackInfo) error {
return nil
}
+1 -1
View File
@@ -98,7 +98,7 @@ func (fs *hellofs) PrepareUpload(_ context.Context, _ *provider.Reference, _ str
return &storage.PrepareUploadResult{VersionCreated: info.NodeExisted}, nil
}
func (fs *hellofs) RollbackUpload(_ context.Context, _ *provider.Reference, _ string, _ bool, _ int64) error {
func (fs *hellofs) RollbackUpload(_ context.Context, _ *provider.Reference, _ string, _ storage.RollbackInfo) error {
return nil
}
+1 -1
View File
@@ -279,7 +279,7 @@ func (d *Driver) PrepareUpload(_ context.Context, _ *provider.Reference, _ strin
return &storage.PrepareUploadResult{VersionCreated: info.NodeExisted}, nil
}
func (d *Driver) RollbackUpload(_ context.Context, _ *provider.Reference, _ string, _ bool, _ int64) error {
func (d *Driver) RollbackUpload(_ context.Context, _ *provider.Reference, _ string, _ storage.RollbackInfo) error {
return nil
}
+1 -1
View File
@@ -453,7 +453,7 @@ func (nc *StorageDriver) PrepareUpload(_ context.Context, _ *provider.Reference,
return &storage.PrepareUploadResult{VersionCreated: info.NodeExisted}, nil
}
func (nc *StorageDriver) RollbackUpload(_ context.Context, _ *provider.Reference, _ string, _ bool, _ int64) error {
func (nc *StorageDriver) RollbackUpload(_ context.Context, _ *provider.Reference, _ string, _ storage.RollbackInfo) error {
return nil
}
@@ -74,6 +74,11 @@ var responses = map[string]Response{
`POST /apps/sciencemesh/~f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c/api/storage/EmptyRecycle `: {200, ``, serverStateEmpty},
`POST /apps/sciencemesh/~f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c/api/storage/GetQuota `: {200, `{"totalBytes":456,"usedBytes":123}`, serverStateEmpty},
// the parent of an upload target, stated for its permissions and its id
`POST /apps/sciencemesh/~f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c/api/storage/GetMD {"ref":{"path":"/"},"mdKeys":[]} EMPTY`: {200, `{"opaque":{},"type":2,"id":{"opaque_id":"fileid-/"},"checksum":{},"etag":"deadbeef","mime_type":"httpd/unix-directory","mtime":{"seconds":1234567890},"path":"/","permission_set":{"initiate_file_upload":true,"stat":true,"list_container":true},"size":12345,"canonical_metadata":{},"arbitrary_metadata":{"metadata":{}}}`, serverStateEmpty},
`POST /apps/sciencemesh/~f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c/api/storage/GetMD {"ref":{"path":"/"},"mdKeys":null} EMPTY`: {404, ``, serverStateEmpty},
`POST /apps/sciencemesh/~f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c/api/storage/GetMD {"ref":{"path":"/"},"mdKeys":null} HOME`: {200, `{"opaque":{},"type":1,"id":{"opaque_id":"fileid-/some/path"},"checksum":{},"etag":"deadbeef","mime_type":"text/plain","mtime":{"seconds":1234567890},"path":"/","permission_set":{},"size":12345,"canonical_metadata":{},"arbitrary_metadata":{"metadata":{"da":"ta","some":"arbi","trary":"meta"}}}`, serverStateHome},
@@ -111,7 +116,13 @@ var responses = map[string]Response{
`POST /apps/sciencemesh/~f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c/api/storage/GetPathByID {"storage_id":"00000000-0000-0000-0000-000000000000","opaque_id":"fileid-/some/path"} EMPTY`: {200, "/subdir", serverStateEmpty},
`POST /apps/sciencemesh/~f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c/api/storage/GetMD {"ref":{"path":"/file"},"mdKeys":null}`: {404, ``, serverStateEmpty},
`POST /apps/sciencemesh/~f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c/api/storage/GetMD {"ref":{"path":"/file"},"mdKeys":null}`: {404, ``, serverStateEmpty},
// the coordinator resolves the upload target itself: the file does not exist yet,
// so it stats the parent for the permissions and the parent id
`POST /apps/sciencemesh/~f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c/api/storage/GetMD {"ref":{"path":"/file"},"mdKeys":[]}`: {404, ``, serverStateEmpty},
// a zero-length upload finishes at once, so the node is created and read back here
`POST /apps/sciencemesh/~f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c/api/storage/TouchFile {"ref":{"resource_id":{"opaque_id":"fileid-/"},"path":"file"},"markprocessing":false,"mtime":"1234567890"}`: {200, ``, serverStateEmpty},
`POST /apps/sciencemesh/~f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c/api/storage/GetMD {"ref":{"resource_id":{"opaque_id":"fileid-/"},"path":"file"},"mdKeys":[]}`: {200, `{"opaque":{},"type":1,"id":{"opaque_id":"fileid-/file"},"checksum":{},"etag":"deadbeef","mime_type":"text/plain","mtime":{"seconds":1234567890},"path":"/file","permission_set":{},"size":0,"canonical_metadata":{},"arbitrary_metadata":{"metadata":{}}}`, serverStateEmpty},
`POST /apps/sciencemesh/~f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c/api/storage/InitiateUpload {"ref":{"path":"/file"},"uploadLength":0,"metadata":{"providerID":""}}`: {200, `{"simple": "yes","tus": "yes"}`, serverStateEmpty},
`POST /apps/sciencemesh/~f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c/api/storage/InitiateUpload {"ref":{"resource_id":{"storage_id":"f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c"},"path":"/versionedFile"},"uploadLength":1,"metadata":{}}`: {200, `{"simple": "yes","tus": "yes"}`, serverStateEmpty},
`POST /apps/sciencemesh/~f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c/api/storage/InitiateUpload {"ref":{"resource_id":{"storage_id":"f7fbf8c8-139b-4376-b307-cf0a8c2d0d9c"},"path":"/versionedFile"},"uploadLength":2,"metadata":{}}`: {200, `{"simple": "yes","tus": "yes"}`, serverStateEmpty},
+1 -1
View File
@@ -181,7 +181,7 @@ func (fs *owncloudsqlfs) PrepareUpload(_ context.Context, _ *provider.Reference,
return &storage.PrepareUploadResult{VersionCreated: info.NodeExisted}, nil
}
func (fs *owncloudsqlfs) RollbackUpload(_ context.Context, _ *provider.Reference, _ string, _ bool, _ int64) error {
func (fs *owncloudsqlfs) RollbackUpload(_ context.Context, _ *provider.Reference, _ string, _ storage.RollbackInfo) error {
return nil
}
+1 -1
View File
@@ -86,6 +86,6 @@ func (fs *s3FS) PrepareUpload(_ context.Context, _ *provider.Reference, _ string
return &storage.PrepareUploadResult{VersionCreated: info.NodeExisted}, nil
}
func (fs *s3FS) RollbackUpload(_ context.Context, _ *provider.Reference, _ string, _ bool, _ int64) error {
func (fs *s3FS) RollbackUpload(_ context.Context, _ *provider.Reference, _ string, _ storage.RollbackInfo) error {
return nil
}
+15 -3
View File
@@ -90,6 +90,18 @@ type PrepareUploadResult struct {
SizeDiff int64
}
// RollbackInfo carries what a driver needs to undo PrepareUpload. NodeID and
// ParentID come from the upload session rather than the node, so a rollback can
// still release the quota of a node whose own metadata has become unreadable.
type RollbackInfo struct {
NodeExisted bool // true when the target node had a prior version; drivers with nothing to undo for new nodes may no-op
SizeDiff int64
NodeID string
ParentID string
Filename string
Size int64
}
// FS is the interface to implement access to the storage.
type FS interface {
// Minimal set for a readonly storage driver
@@ -149,9 +161,9 @@ type FS interface {
// It is the inverse of PrepareUpload: restores previous metadata and reverts the optimistic
// size propagation. The caller (coordinator) is responsible for unmarking the processing flag
// and deleting the upload session files. Drivers that performed no work in PrepareUpload may return nil.
// nodeExisted indicates whether the target node had a prior version; drivers that have nothing
// to undo for new nodes may no-op when nodeExisted is false.
RollbackUpload(ctx context.Context, ref *provider.Reference, sessionID string, nodeExisted bool, sizeDiff int64) error
// Callers must keep the session on a returned error: the rollback is retryable and info
// carries state the driver cannot recover once the session files are gone.
RollbackUpload(ctx context.Context, ref *provider.Reference, sessionID string, info RollbackInfo) error
// Revisions
@@ -28,9 +28,7 @@ import (
"path/filepath"
"strconv"
"strings"
"time"
user "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1"
rpcv1beta1 "github.com/cs3org/go-cs3apis/cs3/rpc/v1beta1"
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
"github.com/jellydator/ttlcache/v2"
@@ -49,7 +47,6 @@ import (
"github.com/owncloud/reva/v2/pkg/events"
"github.com/owncloud/reva/v2/pkg/logger"
"github.com/owncloud/reva/v2/pkg/rgrpc/todo/pool"
"github.com/owncloud/reva/v2/pkg/rhttp/datatx/metrics"
"github.com/owncloud/reva/v2/pkg/storage"
"github.com/owncloud/reva/v2/pkg/storage/utils/chunking"
"github.com/owncloud/reva/v2/pkg/storage/utils/decomposedfs/aspects"
@@ -81,11 +78,9 @@ const (
var (
tracer trace.Tracer
// the coordinator consumes the postprocessing events; reverting a revision is
// the driver's own business
_registeredEvents = []events.Unmarshaller{
events.PostprocessingFinished{},
events.PostprocessingStepFinished{},
events.RestartPostprocessing{},
events.CleanUpload{},
events.RevertRevision{},
}
)
@@ -267,7 +262,9 @@ func New(o *options.Options, aspects aspects.Aspects, log *zerolog.Logger) (stor
return nil, errors.New("need nats for async file processing")
}
ch, err := events.Consume(fs.stream, o.Events.ConsumerGroup, _registeredEvents...)
// a group of its own: the coordinator holds o.Events.ConsumerGroup, and one
// group gets one copy of each event
ch, err := events.Consume(fs.stream, o.Events.ConsumerGroup+"-revisions", _registeredEvents...)
if err != nil {
return nil, err
}
@@ -277,15 +274,15 @@ func New(o *options.Options, aspects aspects.Aspects, log *zerolog.Logger) (stor
}
for i := 0; i < o.Events.NumConsumers; i++ {
go fs.Postprocessing(ch)
go fs.ConsumeRevisionEvents(ch)
}
}
return fs, nil
}
// Postprocessing starts the postprocessing result collector
func (fs *Decomposedfs) Postprocessing(ch <-chan events.Event) {
// ConsumeRevisionEvents starts the revision event collector
func (fs *Decomposedfs) ConsumeRevisionEvents(ch <-chan events.Event) {
log := logger.New()
for event := range ch {
evCtx := context.Background()
@@ -299,180 +296,6 @@ func (fs *Decomposedfs) processEvent(evCtx context.Context, event events.Event,
defer span.End()
switch ev := event.Event.(type) {
case events.PostprocessingFinished:
sublog := log.With().Str("event", "PostprocessingFinished").Str("uploadid", ev.UploadID).Logger()
if ev.ResourceID != nil && ev.ResourceID.GetStorageId() != "" && ev.ResourceID.GetStorageId() != fs.o.MountID {
sublog.Debug().Msg("ignoring event for different storage")
return
}
session, err := fs.sessionStore.Get(ctx, ev.UploadID)
if err != nil {
sublog.Error().Err(err).Msg("Failed to get upload")
return // NOTE: since we can't get the upload, we can't delete the blob
}
ctx = session.Context(ctx)
n, err := session.Node(ctx)
if err != nil {
// The node metadata is unreadable, so this upload can never finish:
// the destination cannot be resolved. Clean the session up instead of
// leaving it behind to be retried forever. Cleanup falls back to the
// session metadata to release the quota.
sublog.Error().Err(err).Msg("could not read node, cleaning up orphaned session")
session.Cleanup(true, true, true, false)
return
}
sublog = log.With().Str("spaceid", session.SpaceID()).Str("nodeid", session.NodeID()).Logger()
if !n.Exists {
sublog.Debug().Msg("node no longer exists")
session.Cleanup(false, true, true, false)
return
}
var (
failed bool
revertNodeMetadata bool
keepUpload bool
)
unmarkPostprocessing := true
switch ev.Outcome {
default:
sublog.Error().Str("outcome", string(ev.Outcome)).Msg("unknown postprocessing outcome - aborting")
fallthrough
case events.PPOutcomeAbort:
failed = true
revertNodeMetadata = true
keepUpload = true
metrics.UploadSessionsAborted.Inc()
case events.PPOutcomeContinue:
if err := session.Finalize(ctx); err != nil {
sublog.Error().Err(err).Msg("could not finalize upload")
failed = true
revertNodeMetadata = false
keepUpload = true
// keep postprocessing status so the upload is not deleted during housekeeping
unmarkPostprocessing = false
} else {
metrics.UploadSessionsFinalized.Inc()
}
case events.PPOutcomeDelete:
failed = true
revertNodeMetadata = true
metrics.UploadSessionsDeleted.Inc()
}
getParent := func() *node.Node {
p, err := n.Parent(ctx)
if err != nil {
sublog.Error().Err(err).Msg("could not read parent")
return nil
}
return p
}
now := time.Now()
if failed {
// if no other upload session is in progress (processing id != session id) or has finished (processing id == "")
latestSession, err := n.ProcessingID(ctx)
if err != nil {
sublog.Error().Err(err).Msg("reading node for session failed")
}
if latestSession == session.ID() {
// propagate reverted sizeDiff after failed postprocessing
if err := fs.tp.Propagate(ctx, n, -session.SizeDiff()); err != nil {
sublog.Error().Err(err).Msg("could not propagate tree size change")
}
}
} else if p := getParent(); p != nil {
// update parent tmtime to propagate etag change after successful postprocessing
_ = p.SetTMTime(ctx, &now)
if err := fs.tp.Propagate(ctx, p, 0); err != nil {
sublog.Error().Err(err).Msg("could not propagate etag change")
}
}
session.Cleanup(revertNodeMetadata, !keepUpload, !keepUpload, unmarkPostprocessing)
var isVersion bool
if session.NodeExists() {
info, err := session.GetInfo(ctx)
if err == nil && info.MetaData["versionsPath"] != "" {
isVersion = true
}
}
if err := events.Publish(
ctx,
fs.stream,
events.UploadReady{
UploadID: ev.UploadID,
Failed: failed,
ExecutingUser: ev.ExecutingUser,
Filename: ev.Filename,
FileRef: &provider.Reference{
ResourceId: &provider.ResourceId{
StorageId: session.ProviderID(),
SpaceId: session.SpaceID(),
OpaqueId: session.SpaceID(),
},
Path: utils.MakeRelativePath(filepath.Join(session.Dir(), session.Filename())),
},
ResourceID: &provider.ResourceId{
StorageId: session.ProviderID(),
SpaceId: session.SpaceID(),
OpaqueId: session.NodeID(),
},
Timestamp: utils.TimeToTS(now),
SpaceOwner: n.SpaceOwnerOrManager(ctx),
IsVersion: isVersion,
ImpersonatingUser: ev.ImpersonatingUser,
},
); err != nil {
sublog.Error().Err(err).Msg("Failed to publish UploadReady event")
}
case events.RestartPostprocessing:
sublog := log.With().Str("event", "RestartPostprocessing").Str("uploadid", ev.UploadID).Logger()
session, err := fs.sessionStore.Get(ctx, ev.UploadID)
if err != nil {
sublog.Error().Err(err).Msg("Failed to get upload")
return
}
n, err := session.Node(ctx)
if err != nil {
sublog.Error().Err(err).Msg("could not read node")
return
}
sublog = log.With().Str("spaceid", session.SpaceID()).Str("nodeid", session.NodeID()).Logger()
s, err := session.URL(ctx)
if err != nil {
sublog.Error().Err(err).Msg("could not create url")
return
}
metrics.UploadSessionsRestarted.Inc()
// restart postprocessing
if err := events.Publish(ctx, fs.stream, events.BytesReceived{
UploadID: session.ID(),
URL: s,
SpaceOwner: n.SpaceOwnerOrManager(ctx),
ExecutingUser: &user.User{Id: &user.UserId{OpaqueId: "postprocessing-restart"}}, // send nil instead?
ResourceID: &provider.ResourceId{SpaceId: n.SpaceID, OpaqueId: n.ID},
Filename: session.Filename(),
Filesize: uint64(session.Size()),
}); err != nil {
sublog.Error().Err(err).Msg("Failed to publish BytesReceived event")
}
case events.CleanUpload:
sublog := log.With().Str("event", "CleanUpload").Str("uploadid", ev.UploadID).Logger()
session, err := fs.sessionStore.Get(ctx, ev.UploadID)
if err != nil {
sublog.Error().Err(err).Msg("Failed to get upload")
return // NOTE: since we can't get the upload, we can't delete the blob
}
session.Cleanup(true, !ev.KeepUpload, !ev.KeepUpload, true)
case events.RevertRevision:
sublog := log.With().Str("event", "RevertRevision").Interface("nodeid", ev.ResourceID).Logger()
if ev.ResourceID != nil && ev.ResourceID.GetStorageId() != "" && ev.ResourceID.GetStorageId() != fs.o.MountID {
@@ -489,132 +312,6 @@ func (fs *Decomposedfs) processEvent(evCtx context.Context, event events.Event,
sublog.Error().Err(err).Msg("Failed to revert revision")
return
}
case events.PostprocessingStepFinished:
sublog := log.With().Str("event", "PostprocessingStepFinished").Str("uploadid", ev.UploadID).Logger()
if ev.ResourceID != nil && ev.ResourceID.GetStorageId() != "" && ev.ResourceID.GetStorageId() != fs.o.MountID {
sublog.Debug().Msg("ignoring event for different storage")
return
}
if ev.FinishedStep != events.PPStepAntivirus {
// atm we are only interested in antivirus results
return
}
res := ev.Result.(events.VirusscanResult)
if res.ErrorMsg != "" {
// scan failed somehow
// Should we handle this here?
return
}
sublog = log.With().Str("scan_description", res.Description).Bool("infected", res.Infected).Logger()
var n *node.Node
switch ev.UploadID {
case "":
// uploadid is empty -> this was an on-demand scan
/* ON DEMAND SCANNING NOT SUPPORTED ATM
ctx := ctxpkg.ContextSetUser(context.Background(), ev.ExecutingUser)
ref := &provider.Reference{ResourceId: ev.ResourceID}
no, err := fs.lu.NodeFromResource(ctx, ref)
if err != nil {
log.Error().Err(err).Interface("resourceID", ev.ResourceID).Msg("Failed to get node after scan")
continue
}
n = no
if ev.Outcome == events.PPOutcomeDelete {
// antivir wants us to delete the file. We must obey and need to
// check if there a previous versions existing
revs, err := fs.ListRevisions(ctx, ref)
if len(revs) == 0 {
if err != nil {
log.Error().Err(err).Interface("resourceID", ev.ResourceID).Msg("Failed to list revisions. Fallback to delete file")
}
// no versions -> trash file
err := fs.Delete(ctx, ref)
if err != nil {
log.Error().Err(err).Interface("resourceID", ev.ResourceID).Msg("Failed to delete infected resource")
continue
}
// now purge it from the recycle bin
if err := fs.PurgeRecycleItem(ctx, &provider.Reference{ResourceId: &provider.ResourceId{SpaceId: n.SpaceID, OpaqueId: n.SpaceID}}, n.ID, "/"); err != nil {
log.Error().Err(err).Interface("resourceID", ev.ResourceID).Msg("Failed to purge infected resource from trash")
}
// remove cache entry in gateway
fs.cache.RemoveStatContext(ctx, ev.ExecutingUser.GetId(), &provider.ResourceId{SpaceId: n.SpaceID, OpaqueId: n.ID})
continue
}
// we have versions - find the newest
versions := make(map[uint64]string) // remember all versions - we need them later
var nv uint64
for _, v := range revs {
versions[v.Mtime] = v.Key
if v.Mtime > nv {
nv = v.Mtime
}
}
// restore newest version
if err := fs.RestoreRevision(ctx, ref, versions[nv]); err != nil {
log.Error().Err(err).Interface("resourceID", ev.ResourceID).Str("revision", versions[nv]).Msg("Failed to restore revision")
continue
}
// now find infected version
revs, err = fs.ListRevisions(ctx, ref)
if err != nil {
log.Error().Err(err).Interface("resourceID", ev.ResourceID).Msg("Error listing revisions after restore")
}
for _, v := range revs {
// we looking for a version that was previously not there
if _, ok := versions[v.Mtime]; ok {
continue
}
if err := fs.DeleteRevision(ctx, ref, v.Key); err != nil {
log.Error().Err(err).Interface("resourceID", ev.ResourceID).Str("revision", v.Key).Msg("Failed to delete revision")
}
}
// remove cache entry in gateway
fs.cache.RemoveStatContext(ctx, ev.ExecutingUser.GetId(), &provider.ResourceId{SpaceId: n.SpaceID, OpaqueId: n.ID})
continue
}
*/
default:
// uploadid is not empty -> this is an async upload
session, err := fs.sessionStore.Get(ctx, ev.UploadID)
if err != nil {
sublog.Error().Err(err).Msg("Failed to get upload")
return
}
n, err = session.Node(ctx)
if err != nil {
sublog.Error().Err(err).Msg("Failed to get node after scan")
return
}
sublog = log.With().Str("spaceid", session.SpaceID()).Str("nodeid", session.NodeID()).Logger()
session.SetScanData(res.Description, res.Scandate)
if err := session.Persist(ctx); err != nil {
sublog.Error().Err(err).Msg("Failed to persist scan results")
}
}
if err := n.SetScanData(ctx, res.Description, res.Scandate); err != nil {
sublog.Error().Err(err).Msg("Failed to set scan results")
return
}
metrics.UploadSessionsScanned.Inc()
default:
log.Error().Interface("event", ev).Msg("Unknown event")
}
@@ -45,6 +45,19 @@ func IsNotExist(err error) bool {
return false
}
// IsErrRange checks for a syscall.ERANGE buried inside an xattr error. listxattr
// returns ERANGE when the set of attribute names grows between the size-probe call
// and the read call (a concurrent setxattr landed in between). This is transient and
// self-clearing once the competing writer finishes its batch.
func IsErrRange(err error) bool {
if xerr, ok := errors.Cause(err).(*xattr.Error); ok {
if serr, ok2 := xerr.Err.(syscall.Errno); ok2 {
return serr == syscall.ERANGE
}
}
return false
}
// IsAttrUnset checks the xattr.ENOATTR from the xattr package which redifines it as ENODATA on platforms that do not natively support it (eg. linux)
// see https://github.com/pkg/xattr/blob/8725d4ccc0fcef59c8d9f0eaf606b3c6f962467a/xattr_linux.go#L19-L22
func IsAttrUnset(err error) bool {
@@ -26,6 +26,7 @@ import (
"strconv"
"strings"
"github.com/owncloud/reva/v2/pkg/appctx"
"github.com/owncloud/reva/v2/pkg/storage/cache"
"github.com/owncloud/reva/v2/pkg/storage/utils/decomposedfs/metadata/prefixes"
"github.com/owncloud/reva/v2/pkg/storage/utils/filelocks"
@@ -82,12 +83,32 @@ func (b XattrsBackend) List(ctx context.Context, filePath string) (attribs []str
return b.list(ctx, filePath, true)
}
const listMaxRetries = 10
func (b XattrsBackend) list(ctx context.Context, filePath string, acquireLock bool) (attribs []string, err error) {
attrs, err := xattr.List(filePath)
if err == nil {
return attrs, nil
}
// ERANGE means a concurrent writer (e.g. the posix inotify assimilate worker)
// mutated the attribute set mid-read. It is transient and self-clearing: retry
// until the set stabilises.
if IsErrRange(err) {
for attempt := 1; attempt <= listMaxRetries; attempt++ {
appctx.GetLogger(ctx).Debug().Err(err).Str("path", filePath).Int("attempt", attempt).Msg("xattr.List ERANGE, retrying")
attrs, err = xattr.List(filePath)
if err == nil {
appctx.GetLogger(ctx).Debug().Str("path", filePath).Int("attempt", attempt).Msg("xattr.List ERANGE recovered after retry")
return attrs, nil
}
if !IsErrRange(err) {
break
}
}
appctx.GetLogger(ctx).Error().Err(err).Str("path", filePath).Msg("xattr.List still failing after ERANGE retries")
}
// listing xattrs failed, try again, either with lock or without
if acquireLock {
f, err := lockedfile.OpenFile(filePath+filelocks.LockFileSuffix, os.O_CREATE|os.O_WRONLY, 0600)
@@ -167,20 +167,16 @@ func (t *Tree) TouchFile(ctx context.Context, n *node.Node, markprocessing bool,
return err
}
// link child name to parent if it is new
// link child name to parent, create-only so a concurrent upload of the same
// new file cannot silently clobber it: the loser gets AlreadyExists and its
// CAS loop re-reads and retries instead of losing the update (OCISDEV-855)
childNameLink := filepath.Join(n.ParentPath(), n.Name)
var link string
link, err = os.Readlink(childNameLink)
if err == nil && link != "../"+n.ID {
if err = os.Remove(childNameLink); err != nil {
return errors.Wrap(err, "Decomposedfs: could not remove symlink child entry")
}
}
if errors.Is(err, fs.ErrNotExist) || link != "../"+n.ID {
relativeNodePath := filepath.Join("../../../../../", lookup.Pathify(n.ID, 4, 2))
if err = os.Symlink(relativeNodePath, childNameLink); err != nil {
return errors.Wrap(err, "Decomposedfs: could not symlink child entry")
relativeNodePath := filepath.Join("../../../../../", lookup.Pathify(n.ID, 4, 2))
if err = os.Symlink(relativeNodePath, childNameLink); err != nil {
if errors.Is(err, fs.ErrExist) {
return errtypes.AlreadyExists(n.Name)
}
return errors.Wrap(err, "Decomposedfs: could not symlink child entry")
}
return t.Propagate(ctx, n, 0)
@@ -21,6 +21,7 @@ package decomposedfs
import (
"context"
"fmt"
iofs "io/fs"
"os"
"path/filepath"
"strings"
@@ -648,10 +649,12 @@ func (fs *Decomposedfs) PrepareUpload(ctx context.Context, ref *provider.Referen
// RollbackUpload reverts the node state written by PrepareUpload after a failed or aborted
// postprocessing run. It restores the previous revision (or purges the node if versioning is
// disabled and no prior version exists) and reverts the optimistic size propagation.
func (fs *Decomposedfs) RollbackUpload(ctx context.Context, ref *provider.Reference, sessionID string, nodeExisted bool, sizeDiff int64) error {
func (fs *Decomposedfs) RollbackUpload(ctx context.Context, ref *provider.Reference, sessionID string, info storage.RollbackInfo) error {
n, err := fs.lu.NodeFromResource(ctx, ref)
if err != nil {
return fmt.Errorf("RollbackUpload: node lookup failed: %w", err)
// The node metadata is unreadable, so the upload can never finish and its
// quota would stay consumed forever.
return fs.rollbackOrphaned(ctx, ref, sessionID, info, err)
}
if !n.Exists {
return nil // nothing was written yet
@@ -669,7 +672,7 @@ func (fs *Decomposedfs) RollbackUpload(ctx context.Context, ref *provider.Refere
return nil
}
if nodeExisted {
if info.NodeExisted {
if err := n.RevertCurrentRevision(ctx, false); err != nil {
return err
}
@@ -681,14 +684,53 @@ func (fs *Decomposedfs) RollbackUpload(ctx context.Context, ref *provider.Refere
}
}
if sizeDiff != 0 {
if err := fs.tp.Propagate(ctx, n, -sizeDiff); err != nil {
if info.SizeDiff != 0 {
if err := fs.tp.Propagate(ctx, n, -info.SizeDiff); err != nil {
appctx.GetLogger(ctx).Error().Err(err).Msg("RollbackUpload: could not revert propagate")
}
}
return nil
}
// node metadata corrupt, use session ids to release quota
func (fs *Decomposedfs) rollbackOrphaned(ctx context.Context, ref *provider.Reference, sessionID string, info storage.RollbackInfo, lookupErr error) error {
if info.NodeID == "" || info.ParentID == "" {
return fmt.Errorf("RollbackUpload: node lookup failed: %w", lookupErr)
}
spaceID := ref.GetResourceId().GetSpaceId()
if spaceID == "" {
return fmt.Errorf("RollbackUpload: node lookup failed: %w", lookupErr)
}
appctx.GetLogger(ctx).Info().Err(lookupErr).Str("sessionid", sessionID).Str("nodeid", info.NodeID).
Msg("node unreadable, rolling back orphaned upload")
n := node.New(spaceID, info.NodeID, info.ParentID, info.Filename, info.Size, sessionID,
provider.ResourceType_RESOURCE_TYPE_FILE, nil, fs.lu)
spaceRoot, err := node.ReadNode(ctx, fs.lu, spaceID, spaceID, false, nil, false)
if err != nil {
return fmt.Errorf("RollbackUpload: space root lookup failed: %w", err)
}
n.SpaceRoot = spaceRoot
if info.SizeDiff != 0 {
// return error so caller keeps session for retry
if err := fs.tp.Propagate(ctx, n, -info.SizeDiff); err != nil {
return fmt.Errorf("RollbackUpload: could not revert propagate: %w", err)
}
}
nodePath := n.InternalPath()
if err := utils.RemoveItem(nodePath); err != nil && !errors.Is(err, iofs.ErrNotExist) {
appctx.GetLogger(ctx).Error().Err(err).Str("nodepath", nodePath).Msg("RollbackUpload: removing orphaned node failed")
}
if err := fs.lu.MetadataBackend().Purge(ctx, nodePath); err != nil && !errors.Is(err, iofs.ErrNotExist) {
appctx.GetLogger(ctx).Error().Err(err).Str("nodepath", nodePath).Msg("RollbackUpload: purging orphaned node metadata failed")
}
// parent holds a child entry pointing to the now-removed node
childEntry := filepath.Join(n.ParentPath(), n.Name)
if err := os.Remove(childEntry); err != nil && !errors.Is(err, iofs.ErrNotExist) {
appctx.GetLogger(ctx).Error().Err(err).Str("path", childEntry).Msg("RollbackUpload: removing orphaned child entry failed")
}
return nil
}
func validateChecksums(ctx context.Context, lu node.PathLookup, n *node.Node, versionPath string) error {
for _, t := range []string{"md5", "sha1", "adler32"} {
key := prefixes.ChecksumPrefix + t
+1 -1
View File
@@ -111,6 +111,6 @@ func (fs *eosfs) PrepareUpload(_ context.Context, _ *provider.Reference, _ strin
return &storage.PrepareUploadResult{VersionCreated: info.NodeExisted}, nil
}
func (fs *eosfs) RollbackUpload(_ context.Context, _ *provider.Reference, _ string, _ bool, _ int64) error {
func (fs *eosfs) RollbackUpload(_ context.Context, _ *provider.Reference, _ string, _ storage.RollbackInfo) error {
return nil
}
+1 -1
View File
@@ -163,7 +163,7 @@ func (fs *localfs) PrepareUpload(_ context.Context, _ *provider.Reference, _ str
return &storage.PrepareUploadResult{VersionCreated: info.NodeExisted}, nil
}
func (fs *localfs) RollbackUpload(_ context.Context, _ *provider.Reference, _ string, _ bool, _ int64) error {
func (fs *localfs) RollbackUpload(_ context.Context, _ *provider.Reference, _ string, _ storage.RollbackInfo) error {
return nil
}
@@ -442,8 +442,8 @@ func (f *FS) PrepareUpload(ctx context.Context, ref *provider.Reference, session
return res, err
}
func (f *FS) RollbackUpload(ctx context.Context, ref *provider.Reference, sessionID string, nodeExisted bool, sizeDiff int64) error {
return f.next.RollbackUpload(ctx, ref, sessionID, nodeExisted, sizeDiff)
func (f *FS) RollbackUpload(ctx context.Context, ref *provider.Reference, sessionID string, info storage.RollbackInfo) error {
return f.next.RollbackUpload(ctx, ref, sessionID, info)
}
func (f *FS) Download(ctx context.Context, ref *provider.Reference, openReaderFunc func(md *provider.ResourceInfo) bool) (*provider.ResourceInfo, io.ReadCloser, error) {
+45
View File
@@ -0,0 +1,45 @@
package upload
import (
"github.com/mitchellh/mapstructure"
)
// AsyncConf is how a service asks for async uploads: whether they are enabled,
// and the consumer subscription to use if they are.
type AsyncConf struct {
Enabled bool
ConsumerGroup string
NumConsumers int
// MountID is the storage id this provider answers for, used to drop
// postprocessing events belonging to other storages.
MountID string
}
// AsyncConfFromDriverConf reads the postprocessing settings off the driver's own
// config keys, so the coordinator and the driver cannot disagree about them.
func AsyncConfFromDriverConf(driverConf map[string]interface{}) AsyncConf {
if driverConf == nil {
return AsyncConf{}
}
var ac struct {
AsyncFileUploads bool `mapstructure:"asyncfileuploads"`
MountID string `mapstructure:"mount_id"`
Events struct {
NumConsumers int `mapstructure:"numconsumers"`
ConsumerGroup string `mapstructure:"consumer_group"`
} `mapstructure:"events"`
}
_ = mapstructure.Decode(driverConf, &ac)
group := ac.Events.ConsumerGroup
if group == "" {
// decomposedfs's default (options.go:177). The coordinator takes over the
// driver's subscription, so it must land in the same group.
group = "dcfs"
}
return AsyncConf{
Enabled: ac.AsyncFileUploads,
ConsumerGroup: group,
NumConsumers: ac.Events.NumConsumers,
MountID: ac.MountID,
}
}
+949
View File
@@ -0,0 +1,949 @@
package upload
import (
"context"
"fmt"
"os"
"path/filepath"
"strings"
"time"
user "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1"
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
"github.com/google/uuid"
"github.com/rs/zerolog"
tusd "github.com/tus/tusd/v2/pkg/handler"
"github.com/owncloud/reva/v2/pkg/appctx"
ctxpkg "github.com/owncloud/reva/v2/pkg/ctx"
"github.com/owncloud/reva/v2/pkg/errtypes"
"github.com/owncloud/reva/v2/pkg/events"
"github.com/owncloud/reva/v2/pkg/rhttp/datatx/metrics"
"github.com/owncloud/reva/v2/pkg/storage"
"github.com/owncloud/reva/v2/pkg/storage/utils/chunking"
"github.com/owncloud/reva/v2/pkg/utils"
)
// Coordinator owns the upload lifecycle: initiation, data transfer and listing.
type Coordinator interface {
// InitiateUpload returns the protocols and ids that bytes can be appended to.
InitiateUpload(ctx context.Context, ref *provider.Reference, uploadLength int64, metadata map[string]string) (map[string]string, error)
// GetUpload returns the session with the given id as a tusd upload.
GetUpload(ctx context.Context, id string) (tusd.Upload, error)
// UseIn registers the coordinator as the tusd data store.
UseIn(composer *tusd.StoreComposer)
// ListUploadSessions returns the upload sessions matching the given filter.
ListUploadSessions(ctx context.Context, filter storage.UploadSessionFilter) ([]storage.UploadSession, error)
// Upload writes the whole body of a non-resumable (PUT) upload and finishes it.
Upload(ctx context.Context, req storage.UploadRequest, uff storage.UploadFinishedFunc) (*provider.ResourceInfo, error)
// StartPostprocessing subscribes to postprocessing results and enables async
// uploads. Call once, before serving requests.
StartPostprocessing(stream events.Consumer, group, mountID string, numConsumers int) error
}
// coordinator is the concrete implementation of Coordinator.
type coordinator struct {
fs storage.FS
store SessionStore
chunkHandler *chunking.ChunkHandler
pub events.Publisher
// async defers the commit to postprocessing. Only StartPostprocessing sets it.
async bool
// mountID is the storage this coordinator serves, used to drop postprocessing
// events belonging to another one.
mountID string
}
// NewCoordinator constructs a coordinator backed by the given driver and store.
func NewCoordinator(fs storage.FS, store SessionStore, chunkFolder string, pub events.Publisher) *coordinator {
c := &coordinator{fs: fs, store: store, pub: pub}
if chunkFolder != "" {
c.chunkHandler = chunking.NewChunkHandler(chunkFolder)
}
return c
}
// NewCoordinatorFromConfig sets up a coordinator and its file store. Pass
// withChunking=false when only initiating uploads: chunk assembly happens on the
// data path, so the storageprovider doesn't need it.
func NewCoordinatorFromConfig(uploadDir string, driverConf map[string]interface{}, fs storage.FS, pub events.Publisher, log *zerolog.Logger, withChunking bool) (Coordinator, error) {
store := NewFileStoreFromConfig(uploadDir, driverConf, log)
if store == nil {
return nil, fmt.Errorf("cannot determine the upload directory, set upload_directory")
}
if err := store.Setup(); err != nil {
return nil, fmt.Errorf("upload directory setup failed: %w", err)
}
chunkFolder := ""
if withChunking {
chunkFolder = store.UploadDir()
}
return NewCoordinator(fs, store, chunkFolder, pub), nil
}
// InitiateUpload resolves the target, then creates and persists the session that
// bytes are appended to.
func (c *coordinator) InitiateUpload(ctx context.Context, ref *provider.Reference, uploadLength int64, metadata map[string]string) (map[string]string, error) {
t, err := c.resolveTarget(ctx, ref, uploadLength, metadata)
if err != nil {
return nil, err
}
session := c.store.New(ctx)
if err := c.populateSession(ctx, session, t, uploadLength, metadata); err != nil {
return nil, err
}
if err := session.TouchBin(); err != nil {
return nil, fmt.Errorf("coordinator: could not create bin file: %w", err)
}
if err := session.Persist(ctx); err != nil {
session.Cleanup(ctx, true, true)
return nil, fmt.Errorf("coordinator: could not persist session: %w", err)
}
metrics.UploadSessionsInitiated.Inc()
// A zero-length upload has no bytes to append, so finish it here.
if uploadLength == 0 {
if _, err := c.finishUpload(ctx, session); err != nil {
return nil, err
}
}
return map[string]string{
"simple": session.ID(),
"tus": session.ID(),
}, nil
}
// populateSession writes the resolved target and the request's metadata into a
// new session.
func (c *coordinator) populateSession(ctx context.Context, session Session, t *uploadTarget, uploadLength int64, metadata map[string]string) error {
session.SetMetadata("filename", t.name)
session.SetStorageValue("NodeName", t.name)
session.SetMetadata("dir", t.dir)
session.SetStorageValue("Dir", t.dir)
session.SetStorageValue("SpaceRoot", t.spaceID)
session.SetStorageValue("NodeParentId", t.parentID)
if t.exists {
session.SetStorageValue("NodeId", t.nodeID)
session.SetStorageValue("NodeExists", "true")
} else {
// A new file has no id yet, and an empty one would resolve to the space root
// (lookup.go:191), so mint a placeholder TouchFile replaces.
session.SetStorageValue("NodeId", uuid.New().String())
}
if t.spaceOwner != nil {
session.SetStorageValue("SpaceOwnerOrManager", t.spaceOwner.GetOpaqueId())
session.SetStorageValue("SpaceOwnerIdp", t.spaceOwner.GetIdp())
session.SetStorageValue("SpaceOwnerType", utils.UserTypeToString(t.spaceOwner.GetType()))
}
if t.chunkName != "" {
session.SetStorageValue("Chunk", t.chunkName)
}
// The ctx is gone by the time the bytes arrive, so record the actor now.
session.SetExecutant(ctxpkg.ContextMustGetUser(ctx))
lockID, _ := ctxpkg.ContextGetLockID(ctx)
session.SetMetadata("lockid", lockID)
initiatorID, _ := ctxpkg.ContextGetInitiator(ctx)
session.SetMetadata("initiatorid", initiatorID)
session.SetSize(uploadLength)
return c.applyRequestMetadata(session, metadata)
}
// applyRequestMetadata stores the client's upload metadata, rejecting a malformed
// checksum. Conditional headers are only recorded, and evaluated at finish.
func (c *coordinator) applyRequestMetadata(session Session, metadata map[string]string) error {
mtime, ok := metadata["mtime"]
if !ok || mtime == "null" {
mtime = utils.TimeToOCMtime(time.Now())
}
session.SetMetadata("mtime", mtime)
session.SetMetadata("providerID", metadata["providerID"])
if v, ok := metadata["expires"]; ok && v != "null" {
session.SetMetadata("expires", v)
}
if _, ok := metadata["sizedeferred"]; ok {
session.SetSizeIsDeferred(true)
}
for _, key := range []string{"if-match", "if-none-match", "if-unmodified-since"} {
if v := metadata[key]; v != "" {
session.SetMetadata(key, v)
}
}
checksum, ok := metadata["checksum"]
if !ok {
return nil
}
parts := strings.SplitN(checksum, " ", 2)
if len(parts) != 2 {
return errtypes.BadRequest("invalid checksum format. must be '[algorithm] [checksum]'")
}
switch parts[0] {
case "sha1", "md5", "adler32":
session.SetMetadata("checksum", checksum)
default:
return errtypes.BadRequest("unsupported checksum algorithm: " + parts[0])
}
return nil
}
// Upload writes the whole body of a non-resumable (PUT) upload and finishes it.
// req.Ref.Path carries the session id minted by InitiateUpload.
func (c *coordinator) Upload(ctx context.Context, req storage.UploadRequest, uff storage.UploadFinishedFunc) (*provider.ResourceInfo, error) {
// The request path arrives rooted, while session ids are stored unrooted.
session, err := c.store.Get(ctx, strings.TrimPrefix(req.Ref.GetPath(), "/"))
if err != nil {
return nil, err
}
// Behind the data gateway the request carries a transfer token, not the user.
ctx = session.Context(ctx)
if chunk := session.Chunk(); chunk != "" { // legacy chunking v1
if c.chunkHandler == nil {
return nil, errtypes.NotSupported("coordinator: chunked uploads require a chunk folder")
}
assembled, assembledSize, done, aErr := c.chunkHandler.Assemble(chunk, req.Body)
if aErr != nil {
return nil, aErr
}
if !done {
// The bytes accumulate in the chunk folder, so this session holds nothing.
session.Cleanup(ctx, true, true)
return nil, errtypes.PartialContent(req.Ref.String())
}
defer assembled.Close()
// The declared length covers only the final chunk.
req.Body, req.Length = assembled, assembledSize
session.SetSize(assembledSize)
}
size, err := session.WriteChunk(ctx, 0, req.Body)
if err != nil {
return nil, err
}
if size != req.Length {
return nil, errtypes.PartialContent("coordinator: unexpected end of stream")
}
ri, err := c.finishUpload(ctx, session)
if err != nil {
return nil, err
}
if uff != nil {
executant := session.Executant()
uff(session.SpaceOwner(), &executant, c.uploadRef(session))
}
return ri, nil
}
// finishUpload creates the node, validates the staged bytes and commits them, or
// hands them to postprocessing.
func (c *coordinator) finishUpload(ctx context.Context, session Session) (*provider.ResourceInfo, error) {
if err := c.touchNode(ctx, session); err != nil {
return nil, err
}
if err := c.markProcessing(ctx, session); err != nil {
return nil, err
}
if err := verifyAndStoreChecksums(ctx, session); err != nil {
c.rollbackMarked(ctx, session)
return nil, err
}
metrics.UploadSessionsBytesReceived.Inc()
if err := c.prepare(ctx, session); err != nil {
return nil, err
}
// Without a publisher there is nothing to hand the bytes to, so commit inline.
if c.async && c.pub != nil && session.Size() > 0 {
if err := c.publishBytesReceived(ctx, session); err != nil {
c.rollbackPrepared(ctx, session, session.SizeDiff())
return nil, err
}
// The node stays flagged and the staged bytes are kept: postprocessing needs
// both to finish later.
return c.uploadedResourceInfo(ctx, session), nil
}
return c.finishSync(ctx, session)
}
// publishBytesReceived hands the staged upload to postprocessing, which downloads
// the bytes from a signed URL to scan them before they are committed.
func (c *coordinator) publishBytesReceived(ctx context.Context, session Session) error {
url, err := session.URL(ctx)
if err != nil {
return err
}
return events.Publish(ctx, c.pub, events.BytesReceived{
UploadID: session.ID(),
URL: url,
SpaceOwner: session.SpaceOwner(),
ExecutingUser: session.ExecutantUser(),
ResourceID: &provider.ResourceId{
StorageId: session.ProviderID(),
SpaceId: session.SpaceID(),
OpaqueId: session.NodeID(),
},
Filename: session.Filename(),
Filesize: uint64(session.Size()),
ImpersonatingUser: impersonatingUser(ctx),
})
}
// touchNode creates the node a new file's upload writes to.
func (c *coordinator) touchNode(ctx context.Context, session Session) error {
if session.NodeExists() {
return nil
}
// The node has no id yet, so address it as a named child of its parent.
pathRef := &provider.Reference{
ResourceId: &provider.ResourceId{
SpaceId: session.SpaceID(),
OpaqueId: session.NodeParentID(),
},
Path: session.Filename(),
}
// MarkProcessing is the coordinator's own call, hence false here.
result, err := c.fs.TouchFile(ctx, pathRef, false, session.Metadata()["mtime"])
if err != nil {
session.Cleanup(ctx, true, true)
if _, ok := err.(errtypes.IsNotFound); ok {
// The parent went away, or the share was revoked, while bytes were in flight.
return errtypes.PreconditionFailed(err.Error())
}
return err
}
// Replaces the placeholder minted at initiate.
session.SetStorageValue("NodeId", result.ResourceID.GetOpaqueId())
session.SetStorageValue("SpaceRoot", result.SpaceID)
if result.SpaceOwner != nil {
session.SetStorageValue("SpaceOwnerOrManager", result.SpaceOwner.GetOpaqueId())
session.SetStorageValue("SpaceOwnerIdp", result.SpaceOwner.GetIdp())
session.SetStorageValue("SpaceOwnerType", utils.UserTypeToString(result.SpaceOwner.GetType()))
}
return nil
}
// markProcessing flags the node as being processed, so clients do not read it
// before its bytes are committed.
func (c *coordinator) markProcessing(ctx context.Context, session Session) error {
ref := session.Reference()
if err := c.fs.MarkProcessing(ctx, &ref, true, session.ID()); err != nil {
// Never marked, so there is nothing to unmark.
session.Cleanup(ctx, true, true)
c.deleteTouchedNode(ctx, session, &ref)
return err
}
metrics.UploadProcessing.Inc()
// The real node id from touchNode must reach the commit, which may run in
// another process.
if err := session.Persist(ctx); err != nil {
c.rollbackMarked(ctx, session)
return err
}
return nil
}
// deleteTouchedNode removes a node this upload created, for the one path where the
// mark itself failed so RollbackUpload has no processing id to key off.
func (c *coordinator) deleteTouchedNode(ctx context.Context, session Session, ref *provider.Reference) {
if session.NodeExists() {
return
}
// Delete is permission-gated, so an Uploader-only role may leave the empty file behind.
if _, err := c.fs.Delete(ctx, ref); err != nil {
appctx.GetLogger(ctx).Error().Err(err).Str("uploadid", session.ID()).Msg("could not delete node after failed upload")
}
}
// prepare has the driver write the node metadata and snapshot the previous
// version, ahead of the commit that writes the bytes.
func (c *coordinator) prepare(ctx context.Context, session Session) error {
ref := session.Reference()
info, err := uploadInfo(session)
if err != nil {
c.rollbackMarked(ctx, session)
return err
}
// A failed PrepareUpload has already undone its own writes.
prepared, err := c.fs.PrepareUpload(ctx, &ref, session.ID(), info)
if err != nil {
c.rollbackMarked(ctx, session)
return err
}
// Persisted, not just held: the commit may run in another process, which can
// only learn these by reading them back.
session.SetSizeDiff(prepared.SizeDiff)
session.SetVersionCreated(prepared.VersionCreated)
if err := session.Persist(ctx); err != nil {
c.rollbackPrepared(ctx, session, prepared.SizeDiff)
return err
}
return nil
}
// rollbackInfo describes the upload to undo. The ids come from the session, which
// is the only place they survive a node whose own metadata has become unreadable.
func rollbackInfo(session Session, sizeDiff int64) storage.RollbackInfo {
return storage.RollbackInfo{
NodeExisted: session.NodeExists(),
SizeDiff: sizeDiff,
NodeID: session.NodeID(),
ParentID: session.NodeParentID(),
Filename: session.Filename(),
Size: session.Size(),
}
}
// rollbackMarked undoes a finish that failed before PrepareUpload ran, so there is
// no revision to revert and nothing was propagated.
func (c *coordinator) rollbackMarked(ctx context.Context, session Session) {
ref := session.Reference()
if !session.NodeExists() {
// Before unmarking: RollbackUpload keys off the processing id.
if err := c.fs.RollbackUpload(ctx, &ref, session.ID(), rollbackInfo(session, 0)); err != nil {
appctx.GetLogger(ctx).Error().Err(err).Str("uploadid", session.ID()).Msg("could not roll back upload")
}
}
c.unmarkProcessing(ctx, session, &ref)
metrics.UploadProcessing.Dec()
session.Cleanup(ctx, true, true)
}
// rollbackPrepared undoes a finish that failed after PrepareUpload succeeded.
func (c *coordinator) rollbackPrepared(ctx context.Context, session Session, sizeDiff int64) {
ref := session.Reference()
// Before unmarking: RollbackUpload keys off the processing id to confirm the
// node is still this upload's.
if err := c.fs.RollbackUpload(ctx, &ref, session.ID(), rollbackInfo(session, sizeDiff)); err != nil {
// The session is the last record of what to undo, so keep it for a retry
// rather than leaving the quota consumed with nothing to reclaim it from.
appctx.GetLogger(ctx).Error().Err(err).Str("uploadid", session.ID()).Msg("could not roll back upload, keeping session")
return
}
c.unmarkProcessing(ctx, session, &ref)
metrics.UploadProcessing.Dec()
session.Cleanup(ctx, true, true)
}
// unmarkProcessing clears the processing flag, tolerating a node the rollback
// already purged.
func (c *coordinator) unmarkProcessing(ctx context.Context, session Session, ref *provider.Reference) {
err := c.fs.MarkProcessing(ctx, ref, false, session.ID())
log := appctx.GetLogger(ctx).With().Str("uploadid", session.ID()).Logger()
switch err.(type) {
case nil:
case errtypes.IsNotFound:
// RollbackUpload purged the node this upload created.
log.Debug().Err(err).Msg("could not unmark processing")
default:
log.Error().Err(err).Msg("could not unmark processing")
}
}
// uploadInfo collects what the driver needs to write the node metadata. The
// preconditions are re-checked there, because the resource may have changed while
// the bytes were being uploaded.
func uploadInfo(session Session) (storage.UploadInfo, error) {
md := session.Metadata()
info := storage.UploadInfo{
NodeExisted: session.NodeExists(),
Size: session.Size(),
Checksums: session.Checksums(),
IfMatch: md["if-match"],
IfNoneMatch: md["if-none-match"],
}
if v := md["mtime"]; v != "" {
mtime, err := utils.MTimeToTime(v)
if err != nil {
return info, errtypes.BadRequest("coordinator: invalid mtime: " + v)
}
info.MTime = mtime
}
if v := md["if-unmodified-since"]; v != "" {
ius, err := time.Parse(time.RFC3339Nano, v)
if err != nil {
return info, errtypes.BadRequest("coordinator: invalid if-unmodified-since: " + v)
}
info.IfUnmodifiedSince = ius
}
return info, nil
}
// verifyAndStoreChecksums hashes the staged bytes, checks them against the
// checksum the client announced, and stores them for the commit.
func verifyAndStoreChecksums(ctx context.Context, session Session) error {
sha1h, md5h, adler32h, err := calculateChecksums(ctx, session.BinPath())
if err != nil {
return err
}
// The announced checksum is not in Metadata(), so read the raw info.
info, err := session.GetInfo(ctx)
if err != nil {
return err
}
if checksum := info.MetaData["checksum"]; checksum != "" {
parts := strings.SplitN(checksum, " ", 2)
if len(parts) != 2 {
return errtypes.BadRequest("invalid checksum format. must be '[algorithm] [checksum]'")
}
var checkErr error
switch parts[0] {
case "sha1":
checkErr = checkHash(parts[1], sha1h)
case "md5":
checkErr = checkHash(parts[1], md5h)
case "adler32":
checkErr = checkHash(parts[1], adler32h)
default:
checkErr = errtypes.BadRequest("unsupported checksum algorithm: " + parts[0])
}
if checkErr != nil {
return checkErr
}
}
session.SetChecksums(sha1h.Sum(nil), md5h.Sum(nil), adler32h.Sum(nil))
return nil
}
// finishSync commits the staged bytes for an inline upload, discarding the
// session if the commit fails: the client is still waiting and will retry, so
// keeping the bytes would only leak them.
func (c *coordinator) finishSync(ctx context.Context, session Session) (*provider.ResourceInfo, error) {
ri, err := c.commit(ctx, session)
if err != nil {
c.rollbackPrepared(ctx, session, session.SizeDiff())
return nil, err
}
return ri, nil
}
// finishAsync commits the staged bytes for an upload postprocessing has cleared.
// A failure here keeps the node marked and the session on disk, so an admin can
// retry with RestartPostprocessing or discard it with CleanUpload. Nobody is
// waiting on the response any more, so there is no retry but theirs.
func (c *coordinator) finishAsync(ctx context.Context, session Session) error {
_, err := c.commit(ctx, session)
return err
}
// commit writes the staged bytes through the driver seam and, on success, unmarks
// the node and retires the session. It leaves a failure untouched for the caller
// to handle, the two finish paths wanting opposite things.
func (c *coordinator) commit(ctx context.Context, session Session) (*provider.ResourceInfo, error) {
ref := session.Reference()
f, err := os.Open(session.BinPath())
if err != nil {
return nil, err
}
// The verdict rides along with the bytes, so a committed blob always carries
// the one it was cleared under. Empty on the inline path, which never scans.
scanResult, scanDate := session.ScanData()
// CommitUpload does not own the body; we opened it, so we close it.
err = c.fs.CommitUpload(ctx, &ref, session.ID(), storage.UploadSource{
Body: f,
Length: session.Size(),
ScanResult: scanResult,
ScanDate: scanDate,
})
f.Close()
if err != nil {
return nil, err
}
// Not unmarkProcessing: the commit succeeded, so a missing node is unexpected.
if err := c.fs.MarkProcessing(ctx, &ref, false, session.ID()); err != nil {
appctx.GetLogger(ctx).Error().Err(err).Str("uploadid", session.ID()).Msg("could not unmark processing")
}
metrics.UploadProcessing.Dec()
session.Cleanup(ctx, true, true)
metrics.UploadSessionsFinalized.Inc()
ri := c.uploadedResourceInfo(ctx, session)
c.publishUploadReady(ctx, session, ri)
return ri, nil
}
// uploadedResourceInfo describes the uploaded resource for the caller, which turns
// it into PUT response headers.
//
// TODO: the fallback carries no etag, which a write-only share used to get.
// Returning it through the seam is the proper fix.
func (c *coordinator) uploadedResourceInfo(ctx context.Context, session Session) *provider.ResourceInfo {
ref := session.Reference()
// The driver owns the resulting etag and mtime, so read them back.
ri, err := c.fs.GetMD(ctx, &ref, nil, nil)
if err == nil {
// Drivers do not know their own mount id and the dataprovider does not stamp
// it, so an unstamped id would not resolve for the client.
if ri.GetId().GetStorageId() == "" {
ri.Id.StorageId = session.ProviderID()
}
return ri
}
// GetMD is permission-gated, so a write-only share cannot stat what it just
// uploaded. That must not fail the upload.
appctx.GetLogger(ctx).Debug().Err(err).Str("uploadid", session.ID()).Msg("could not stat uploaded resource")
fallback := &provider.ResourceInfo{Id: ref.GetResourceId(), Size: uint64(session.Size())}
if mtime, mErr := utils.MTimeToTime(session.Metadata()["mtime"]); mErr == nil {
fallback.Mtime = utils.TimeToTS(mtime)
}
return fallback
}
// publishUploadReady announces that the file is available. Consumers such as the
// search indexer only listen for UploadReady, so without it they would never learn
// about an upload the coordinator committed inline.
func (c *coordinator) publishUploadReady(ctx context.Context, session Session, ri *provider.ResourceInfo) {
if c.pub == nil {
return
}
if err := events.Publish(ctx, c.pub, events.UploadReady{
UploadID: session.ID(),
Filename: session.Filename(),
SpaceOwner: session.SpaceOwner(),
ExecutingUser: session.ExecutantUser(),
FileRef: c.uploadRef(session),
ResourceID: ri.GetId(),
Timestamp: utils.TSNow(),
IsVersion: session.VersionCreated(),
ImpersonatingUser: impersonatingUser(ctx),
}); err != nil {
appctx.GetLogger(ctx).Error().Err(err).Str("uploadid", session.ID()).Msg("failed to publish UploadReady event")
}
}
// uploadTarget is what an upload needs to know about its destination
type uploadTarget struct {
// exists distinguishes an overwrite from a new file.
exists bool
// chunkName is set for legacy chunking-v1 uploads only.
chunkName string
nodeID string
spaceID string
parentID string
dir string
name string
spaceOwner *user.UserId
}
// resolveTarget locates the file an upload writes to, and rejects an upload that
// may not proceed.
func (c *coordinator) resolveTarget(ctx context.Context, ref *provider.Reference, uploadLength int64, metadata map[string]string) (*uploadTarget, error) {
t := &uploadTarget{}
if chunking.IsChunked(ref.GetPath()) { // check legacy chunking v1
var err error
ref, t.chunkName, err = rewriteChunkedRef(ref)
if err != nil {
return nil, err
}
}
// TODO: GetMD reports a file hidden by a deny-grant as NotFound, so the upload
// fails late with 409 instead of 403. Needs a permission-free resolve.
existing, err := c.fs.GetMD(ctx, ref, []string{}, []string{})
switch err.(type) {
case nil:
t.exists = true
case errtypes.IsNotFound:
t.exists = false
default:
return nil, err
}
if err := c.checkQuota(ctx, ref, uploadLength, existing); err != nil {
return nil, err
}
if t.exists {
if err := c.describeExisting(ctx, ref, existing, metadata, t); err != nil {
return nil, err
}
} else if err := c.describeNew(ctx, ref, t); err != nil {
return nil, err
}
if t.name == "" {
return nil, errtypes.BadRequest("coordinator: missing filename in ref")
}
if t.dir == "" {
return nil, errtypes.BadRequest("coordinator: could not determine upload directory")
}
return t, nil
}
// checkQuota rejects an upload that would not fit in the space, counting only
// the bytes it adds.
func (c *coordinator) checkQuota(ctx context.Context, ref *provider.Reference, uploadLength int64, existing *provider.ResourceInfo) error {
if uploadLength < 0 {
return nil
}
spaceRef := &provider.Reference{ResourceId: &provider.ResourceId{
StorageId: ref.GetResourceId().GetStorageId(),
SpaceId: ref.GetResourceId().GetSpaceId(),
}}
_, _, remaining, err := c.fs.GetQuota(ctx, spaceRef)
if err != nil {
return nil
}
netRequired := uint64(uploadLength)
if existingSize := existing.GetSize(); existingSize < netRequired {
netRequired -= existingSize
} else {
netRequired = 0
}
if remaining < netRequired {
return errtypes.InsufficientStorage("quota exceeded")
}
return nil
}
// describeExisting fills in the target from the file being overwritten.
func (c *coordinator) describeExisting(ctx context.Context, ref *provider.Reference, existing *provider.ResourceInfo, metadata map[string]string, t *uploadTarget) error {
if !existing.GetPermissionSet().GetInitiateFileUpload() {
return errtypes.PermissionDenied(ref.GetPath())
}
if existing.GetType() == provider.ResourceType_RESOURCE_TYPE_CONTAINER {
return errtypes.PreconditionFailed("resource is not a file")
}
t.nodeID = existing.GetId().GetOpaqueId()
t.spaceID = existing.GetId().GetSpaceId()
t.parentID = existing.GetParentId().GetOpaqueId()
t.name = existing.GetName()
t.spaceOwner = c.spaceOwnerOrManager(ctx, existing.GetOwner(), t.spaceID)
// GetMD returns only the basename for id-based refs, so ask for the full path.
relPath := existing.GetPath()
if utils.IsRelativeReference(ref) {
if full, err := c.fs.GetPathByID(ctx, existing.GetId()); err == nil {
relPath = full
}
}
t.dir = filepath.Dir(relPath)
// Lock before precondition, the order main checks them in (upload.go:293-302).
if err := c.checkLock(ctx, ref); err != nil {
return err
}
if metadata["if-none-match"] == "*" {
return errtypes.Aborted(fmt.Sprintf("parent %s already has a child %s, id %s", t.parentID, t.name, t.nodeID))
}
return nil
}
// spaceOwnerOrManager resolves the space owner, falling back to a manager.
func (c *coordinator) spaceOwnerOrManager(ctx context.Context, owner *user.UserId, spaceID string) *user.UserId {
// A space with no personal owner stores a SPACE_OWNER placeholder (spaces.go:145).
if owner != nil && owner.GetType() != user.UserType_USER_TYPE_SPACE_OWNER {
return owner
}
grants, err := c.fs.ListGrants(ctx, &provider.Reference{ResourceId: &provider.ResourceId{
SpaceId: spaceID,
OpaqueId: spaceID,
}})
if err != nil {
return nil
}
// Grants come back in map order, so several managers resolve to an arbitrary one.
for _, g := range grants {
// Group grants carry no user id.
uid := g.GetGrantee().GetUserId()
if uid == nil {
continue
}
p := g.GetPermissions()
if p.GetStat() && p.GetListContainer() && p.GetInitiateFileDownload() {
return uid
}
}
return nil
}
// checkLock rejects an upload that conflicts with a lock held on the file.
func (c *coordinator) checkLock(ctx context.Context, ref *provider.Reference) error {
// An unlocked file and a driver without locks both error, so only a lock we
// actually read counts as one.
diskLock, err := c.fs.GetLock(ctx, ref)
if err != nil {
diskLock = nil
}
contextLockID, _ := ctxpkg.ContextGetLockID(ctx)
switch {
case diskLock == nil && contextLockID != "":
return errtypes.Aborted("not locked")
case diskLock == nil:
return nil
case contextLockID == "":
return errtypes.Locked(diskLock.LockId)
case contextLockID != diskLock.LockId:
return errtypes.Aborted("mismatching lock")
}
return nil
}
// describeNew fills in the target for a file that does not exist yet, from its
// parent directory.
func (c *coordinator) describeNew(ctx context.Context, ref *provider.Reference, t *uploadTarget) error {
t.spaceID = ref.GetResourceId().GetSpaceId()
t.dir = filepath.Dir(ref.GetPath())
t.name = filepath.Base(ref.GetPath())
parentRef := &provider.Reference{ResourceId: ref.GetResourceId(), Path: t.dir}
parentMD, err := c.fs.GetMD(ctx, parentRef, []string{}, []string{})
switch err.(type) {
case nil:
case errtypes.IsNotFound:
return c.missingParentError(ctx, ref, t.dir, err)
default:
return err
}
if !parentMD.GetPermissionSet().GetInitiateFileUpload() {
return errtypes.PermissionDenied(ref.GetPath())
}
t.parentID = parentMD.GetId().GetOpaqueId()
t.spaceID = parentMD.GetId().GetSpaceId()
// An id-based ref yields a relative dir ("."), so ask for the parent's full path.
if utils.IsRelativeReference(ref) {
if parentPath, pErr := c.fs.GetPathByID(ctx, parentMD.GetId()); pErr == nil {
t.dir = parentPath
}
}
return nil
}
// missingParentError tells a missing directory apart from one that is only
// invisible to the caller: a visible ancestor means it is missing.
func (c *coordinator) missingParentError(ctx context.Context, ref *provider.Reference, dir string, notFound error) error {
for ancestor := dir; ancestor != "." && ancestor != "/"; {
ancestor = filepath.Dir(ancestor)
ancestorRef := &provider.Reference{ResourceId: ref.GetResourceId(), Path: ancestor}
if _, err := c.fs.GetMD(ctx, ancestorRef, []string{}, []string{}); err == nil {
return errtypes.PreconditionFailed(notFound.Error())
}
}
return errtypes.PermissionDenied(ref.GetPath())
}
// rewriteChunkedRef turns a legacy chunking-v1 path into a reference to the real
// target file, plus the chunk name.
func rewriteChunkedRef(ref *provider.Reference) (*provider.Reference, string, error) {
ci, err := chunking.GetChunkBLOBInfo(ref.GetPath())
if err != nil {
return nil, "", errtypes.BadRequest(err.Error())
}
return &provider.Reference{ResourceId: ref.ResourceId, Path: ci.Path}, filepath.Base(ref.GetPath()), nil
}
// ListUploadSessions returns the upload sessions matching the given filter.
func (c *coordinator) ListUploadSessions(ctx context.Context, filter storage.UploadSessionFilter) ([]storage.UploadSession, error) {
// Only the driver can resolve a session's node, so refuse rather than
// silently report every session as a match.
if filter.Orphaned != nil {
return nil, errtypes.NotSupported("coordinator: the orphaned filter is not supported")
}
var sessions []Session
if filter.ID != nil && *filter.ID != "" {
session, err := c.store.Get(ctx, *filter.ID)
if err != nil {
return nil, err
}
sessions = []Session{session}
} else {
var err error
sessions, err = c.store.List(ctx)
if err != nil {
return nil, err
}
}
filtered := []storage.UploadSession{}
now := time.Now()
for _, session := range sessions {
if filter.Processing != nil && *filter.Processing != session.IsProcessing() {
continue
}
if filter.Expired != nil {
if *filter.Expired {
if now.Before(session.Expires()) {
continue
}
} else {
if now.After(session.Expires()) {
continue
}
}
}
if filter.HasVirus != nil {
sr, _ := session.ScanData()
infected := sr != ""
if *filter.HasVirus != infected {
continue
}
}
filtered = append(filtered, session)
}
return filtered, nil
}
// uploadRef builds the reference upload events carry: the space root, plus the
// file's path within it.
func (c *coordinator) uploadRef(session Session) *provider.Reference {
return &provider.Reference{
ResourceId: &provider.ResourceId{
StorageId: session.ProviderID(),
SpaceId: session.SpaceID(),
OpaqueId: session.SpaceID(),
},
Path: utils.MakeRelativePath(filepath.Join(session.Dir(), session.Filename())),
}
}
// impersonatingUser returns the real actor behind a borrowed identity, which
// public link and OCM auth record in the request user's opaque.
func impersonatingUser(ctx context.Context) *user.User {
u, ok := ctxpkg.ContextGetUser(ctx)
if !ok || !utils.ExistsInOpaque(u.GetOpaque(), "impersonating-user") {
return nil
}
impersonating := &user.User{}
if err := utils.ReadJSONFromOpaque(u.GetOpaque(), "impersonating-user", impersonating); err != nil {
appctx.GetLogger(ctx).Error().Err(err).Msg("could not read impersonating user")
return nil
}
return impersonating
}
+205
View File
@@ -0,0 +1,205 @@
package upload
import (
"context"
"encoding/json"
iofs "io/fs"
"os"
"path/filepath"
"strings"
"syscall"
"github.com/google/uuid"
"github.com/mitchellh/mapstructure"
"github.com/pkg/errors"
"github.com/rs/zerolog"
tusd "github.com/tus/tusd/v2/pkg/handler"
"github.com/owncloud/reva/v2/pkg/appctx"
)
// TokenOptions carries the JWT-signing configuration needed to produce transfer
// URLs for the postprocessing service.
type TokenOptions struct {
DownloadEndpoint string
DataGatewayEndpoint string
TransferSharedSecret string
TransferExpires int64
}
// SessionStore abstracts upload-session persistence for the Coordinator.
type SessionStore interface {
New(ctx context.Context) Session
Get(ctx context.Context, id string) (Session, error)
List(ctx context.Context) ([]Session, error)
}
// FileStore is a filesystem-backed SessionStore. Sessions are stored as a pair
// of files in the upload directory:
//
// - <id>.info — JSON-encoded tusd.FileInfo
// - <id> — staged binary bytes
//
// This is the same on-disk format used by OcisStore so existing sessions
// survive a rolling deploy that switches to FileStore.
type FileStore struct {
uploadDir string
opts TokenOptions
log *zerolog.Logger
}
// FileStoreFromDriverConf builds a FileStore from a reva driver config map.
// Returns nil if the config carries no upload path (driver does not support
// coordinated uploads). Each service that mounts the same driver calls this
// independently.
func FileStoreFromDriverConf(driverConf map[string]interface{}, log *zerolog.Logger) *FileStore {
if driverConf == nil {
return nil
}
// storage_root is the ocm driver's spelling of root; it stages uploads under
// the same <root>/uploads/ layout the decomposedfs family uses.
type driverRootConf struct {
Root string `mapstructure:"root"`
UploadDirectory string `mapstructure:"upload_directory"`
StorageRoot string `mapstructure:"storage_root"`
}
var rc driverRootConf
_ = mapstructure.Decode(driverConf, &rc)
// upload_directory already names the upload directory itself, the way
// decomposedfs reads it (options.go:172, posix tree.go:168). The other two are
// storage roots that stage uploads in a subdirectory, so only they get joined.
if rc.UploadDirectory != "" {
return newFileStoreWithTokens(rc.UploadDirectory, driverConf, log)
}
root := rc.Root
if root == "" {
root = rc.StorageRoot
}
if root == "" {
return nil
}
return newFileStoreWithTokens(filepath.Join(root, "uploads"), driverConf, log)
}
// NewFileStoreFromConfig builds a FileStore staging uploads in uploadDir when
// set, falling back to the active driver config. This allows drivers that have
// no local root (e.g. KW) to still get a coordinator by setting
// upload_directory at the service level rather than inside the driver.
// Returns nil only when neither source resolves to a non-empty path.
func NewFileStoreFromConfig(uploadDir string, driverConf map[string]interface{}, log *zerolog.Logger) *FileStore {
if uploadDir != "" {
// Still take the tokens from the driver config: they sign the transfer URL
// that postprocessing downloads the staged bytes from, and a service-level
// upload directory says nothing about them.
return newFileStoreWithTokens(uploadDir, driverConf, log)
}
return FileStoreFromDriverConf(driverConf, log)
}
func newFileStoreWithTokens(uploadDir string, driverConf map[string]interface{}, log *zerolog.Logger) *FileStore {
type tokenConf struct {
DownloadEndpoint string `mapstructure:"download_endpoint"`
DataGatewayEndpoint string `mapstructure:"datagateway_endpoint"`
TransferSharedSecret string `mapstructure:"transfer_shared_secret"`
TransferExpires int64 `mapstructure:"transfer_expires"`
}
var tc tokenConf
if tokens, ok := driverConf["tokens"]; ok {
_ = mapstructure.Decode(tokens, &tc)
}
return NewFileStore(uploadDir, TokenOptions{
DownloadEndpoint: tc.DownloadEndpoint,
DataGatewayEndpoint: tc.DataGatewayEndpoint,
TransferSharedSecret: tc.TransferSharedSecret,
TransferExpires: tc.TransferExpires,
}, log)
}
// NewFileStore creates a FileStore staging uploads in uploadDir.
// uploadDir must be on a shared filesystem when multiple pods handle the same space.
func NewFileStore(uploadDir string, opts TokenOptions, log *zerolog.Logger) *FileStore {
return &FileStore{uploadDir: uploadDir, opts: opts, log: log}
}
// UploadDir returns the directory this FileStore stages uploads in.
func (fs *FileStore) UploadDir() string {
return fs.uploadDir
}
// Setup creates the upload directory eagerly so permission problems are caught
// at startup rather than on the first upload.
func (fs *FileStore) Setup() error {
return os.MkdirAll(fs.uploadDir, 0700)
}
// New allocates a fresh session with a new UUID.
func (fs *FileStore) New(_ context.Context) Session {
return &FileSession{
store: fs,
info: tusd.FileInfo{
ID: uuid.New().String(),
Storage: map[string]string{
"Type": "OCISStore",
},
MetaData: tusd.MetaData{},
},
}
}
// Get loads the session with the given id from disk.
func (fs *FileStore) Get(ctx context.Context, id string) (Session, error) {
infoPath := fileSessionPath(fs.uploadDir, id)
data, err := os.ReadFile(infoPath)
if err != nil {
if pathErr, ok := err.(*os.PathError); ok && pathErr.Err == syscall.ESTALE {
return nil, tusd.ErrNotFound
}
if errors.Is(err, iofs.ErrNotExist) {
return nil, tusd.ErrNotFound
}
return nil, err
}
var info tusd.FileInfo
if err := json.Unmarshal(data, &info); err != nil {
return nil, err
}
session := &FileSession{store: fs, info: info}
stat, err := os.Stat(session.binPath())
if err != nil {
if os.IsNotExist(err) {
return nil, tusd.ErrNotFound
}
return nil, err
}
session.info.Offset = stat.Size()
return session, nil
}
// List returns all sessions found in the upload directory.
func (fs *FileStore) List(ctx context.Context) ([]Session, error) {
infoFiles, err := filepath.Glob(filepath.Join(fs.uploadDir, "*.info"))
if err != nil {
return nil, err
}
sessions := make([]Session, 0, len(infoFiles))
for _, path := range infoFiles {
id := strings.TrimSuffix(filepath.Base(path), ".info")
session, err := fs.Get(ctx, id)
if err != nil {
appctx.GetLogger(ctx).Error().Str("path", path).Err(err).Msg("filestore: could not load session")
continue
}
sessions = append(sessions, session)
}
return sessions, nil
}
+226
View File
@@ -0,0 +1,226 @@
// This file holds the postprocessing result collector: the second half of an
// async upload. finishUpload stages the bytes and publishes BytesReceived; the
// postprocessing service scans them and reports back here, and only then are the
// bytes committed through the driver seam.
//
// It is driver-agnostic on purpose: this logic used to live inside decomposedfs,
// which meant only that driver could offer async uploads.
package upload
import (
"context"
"errors"
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
"github.com/rs/zerolog"
"github.com/owncloud/reva/v2/pkg/appctx"
"github.com/owncloud/reva/v2/pkg/events"
"github.com/owncloud/reva/v2/pkg/rhttp/datatx/metrics"
"github.com/owncloud/reva/v2/pkg/utils"
)
// RegisteredEvents are the postprocessing events the coordinator consumes.
var RegisteredEvents = []events.Unmarshaller{
events.PostprocessingFinished{},
events.PostprocessingStepFinished{},
events.RestartPostprocessing{},
events.CleanUpload{},
}
// StartPostprocessing subscribes to postprocessing results and switches the
// coordinator over to async uploads: from here on finished uploads stage their
// bytes and wait for a scan verdict instead of committing inline.
//
// The two go together on purpose. Deferring a commit is only safe if something
// will arrive to finish it, so there is no way to enable async without a running
// consumer, and none to run a consumer that never receives work.
//
// mountID is the storage id this provider serves. Postprocessing events are
// broadcast to every provider, so events for other storages must be dropped;
// pass "" only in tests, where a single provider sees a private stream.
//
// numConsumers goroutines share the subscription. Call once, before serving
// requests. Fails without a publisher: nothing would hand uploads to
// postprocessing, so every one of them would wait for a verdict that never comes.
func (c *coordinator) StartPostprocessing(stream events.Consumer, group, mountID string, numConsumers int) error {
if c.pub == nil {
return errors.New("coordinator: async uploads need an event publisher")
}
ch, err := events.Consume(stream, group, RegisteredEvents...)
if err != nil {
return err
}
if numConsumers <= 0 {
numConsumers = 1
}
c.mountID = mountID
c.async = true
for i := 0; i < numConsumers; i++ {
go c.Postprocessing(ch)
}
return nil
}
// Postprocessing consumes postprocessing results until ch is closed. Run it in
// its own goroutine, one per configured consumer.
func (c *coordinator) Postprocessing(ch <-chan events.Event) {
for event := range ch {
c.processEvent(context.Background(), event)
}
}
// servesStorage reports whether an event is for the storage this coordinator
// serves. Postprocessing runs as a separate service and broadcasts its results to
// every storage provider, so each has to recognise its own. Events that name no
// storage predate this and are accepted.
func (c *coordinator) servesStorage(id *provider.ResourceId) bool {
if c.mountID == "" || id.GetStorageId() == "" {
return true
}
return id.GetStorageId() == c.mountID
}
func (c *coordinator) processEvent(ctx context.Context, event events.Event) {
log := appctx.GetLogger(ctx)
switch ev := event.Event.(type) {
case events.PostprocessingFinished:
if !c.servesStorage(ev.ResourceID) {
return
}
c.onPostprocessingFinished(ctx, ev, log)
case events.RestartPostprocessing:
c.onRestartPostprocessing(ctx, ev, log)
case events.CleanUpload:
session, err := c.store.Get(ctx, ev.UploadID)
if err != nil {
log.Error().Err(err).Str("uploadid", ev.UploadID).Msg("CleanUpload: could not load session")
return
}
if !ev.KeepUpload {
c.rollbackPrepared(ctx, session, session.SizeDiff())
} else {
c.rollbackNode(ctx, session)
metrics.UploadProcessing.Dec()
}
case events.PostprocessingStepFinished:
if !c.servesStorage(ev.ResourceID) {
return
}
if ev.FinishedStep != events.PPStepAntivirus {
// only the antivirus result is recorded on the session
return
}
res, ok := ev.Result.(events.VirusscanResult)
if !ok || res.ErrorMsg != "" {
// the scan itself failed; PostprocessingFinished decides the outcome
return
}
session, err := c.store.Get(ctx, ev.UploadID)
if err != nil {
// an empty upload id means an on-demand scan, which has no session
if ev.UploadID != "" {
log.Error().Err(err).Str("uploadid", ev.UploadID).Msg("PostprocessingStepFinished: could not load session")
}
return
}
session.SetScanData(res.Description, res.Scandate)
metrics.UploadSessionsScanned.Inc()
if err := session.Persist(ctx); err != nil {
log.Error().Err(err).Str("uploadid", ev.UploadID).Msg("could not persist scan result")
}
}
}
// onPostprocessingFinished completes or discards an upload according to the
// outcome postprocessing reported.
func (c *coordinator) onPostprocessingFinished(ctx context.Context, ev events.PostprocessingFinished, log *zerolog.Logger) {
session, err := c.store.Get(ctx, ev.UploadID)
if err != nil {
// Without the session we cannot reach the staged bytes, so they are leaked
// here. Housekeeping cleans them up later.
log.Error().Err(err).Str("uploadid", ev.UploadID).Msg("PostprocessingFinished: could not load session")
return
}
ctx = session.Context(ctx)
log = appctx.GetLogger(ctx)
switch ev.Outcome {
case events.PPOutcomeContinue:
if err := c.finishAsync(ctx, session); err != nil {
// Deliberately left as it is: the node stays marked and the session on
// disk, so this can be retried with RestartPostprocessing or discarded
// with CleanUpload rather than silently losing the bytes.
log.Error().Err(err).Str("uploadid", ev.UploadID).Msg("could not commit upload after postprocessing")
c.publishUploadFailed(ctx, session, ev)
}
return
case events.PPOutcomeAbort:
metrics.UploadSessionsAborted.Inc()
// Keep the staged bytes: an abort is a transient failure and the upload can
// be restarted with RestartPostprocessing.
c.rollbackNode(ctx, session)
case events.PPOutcomeDelete:
metrics.UploadSessionsDeleted.Inc()
c.rollbackPrepared(ctx, session, session.SizeDiff())
default:
log.Error().Str("outcome", string(ev.Outcome)).Str("uploadid", ev.UploadID).Msg("unknown postprocessing outcome, aborting")
metrics.UploadSessionsAborted.Inc()
c.rollbackNode(ctx, session)
}
c.publishUploadFailed(ctx, session, ev)
}
// onRestartPostprocessing re-publishes BytesReceived so a previously aborted
// upload gets another postprocessing run.
func (c *coordinator) onRestartPostprocessing(ctx context.Context, ev events.RestartPostprocessing, log *zerolog.Logger) {
session, err := c.store.Get(ctx, ev.UploadID)
if err != nil {
log.Error().Err(err).Str("uploadid", ev.UploadID).Msg("RestartPostprocessing: could not load session")
return
}
metrics.UploadSessionsRestarted.Inc()
if err := c.publishBytesReceived(session.Context(ctx), session); err != nil {
log.Error().Err(err).Str("uploadid", ev.UploadID).Msg("could not restart postprocessing")
}
}
// rollbackNode reverts the node to its pre-upload state but keeps the staged
// bytes and the session, so postprocessing can be restarted.
func (c *coordinator) rollbackNode(ctx context.Context, session Session) {
ref := session.Reference()
if err := c.fs.RollbackUpload(ctx, &ref, session.ID(), rollbackInfo(session, session.SizeDiff())); err != nil {
appctx.GetLogger(ctx).Error().Err(err).Str("uploadid", session.ID()).Msg("could not roll back upload, keeping session")
return
}
c.unmarkProcessing(ctx, session, &ref)
}
// publishUploadFailed tells consumers the upload will not become available.
// Clients wait on UploadReady, so staying silent would leave them hanging.
func (c *coordinator) publishUploadFailed(ctx context.Context, session Session, ev events.PostprocessingFinished) {
if c.pub == nil {
return
}
if err := events.Publish(ctx, c.pub, events.UploadReady{
UploadID: session.ID(),
Failed: true,
Filename: session.Filename(),
SpaceOwner: session.SpaceOwner(),
ExecutingUser: ev.ExecutingUser,
FileRef: c.uploadRef(session),
ResourceID: &provider.ResourceId{
StorageId: session.ProviderID(),
SpaceId: session.SpaceID(),
OpaqueId: session.NodeID(),
},
Timestamp: utils.TSNow(),
IsVersion: session.VersionCreated(),
ImpersonatingUser: ev.ImpersonatingUser,
}); err != nil {
appctx.GetLogger(ctx).Error().Err(err).Str("uploadid", session.ID()).Msg("failed to publish UploadReady event")
}
}
+491
View File
@@ -0,0 +1,491 @@
package upload
import (
"context"
"crypto/md5" //nolint:gosec
"crypto/sha1" //nolint:gosec
"encoding/hex"
"encoding/json"
"fmt"
"hash"
"hash/adler32"
"io"
"os"
"path/filepath"
"strconv"
"strings"
"time"
userpb "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1"
provider "github.com/cs3org/go-cs3apis/cs3/storage/provider/v1beta1"
typespb "github.com/cs3org/go-cs3apis/cs3/types/v1beta1"
"github.com/golang-jwt/jwt/v5"
"github.com/google/renameio/v2"
"github.com/pkg/errors"
tusd "github.com/tus/tusd/v2/pkg/handler"
"github.com/owncloud/reva/v2/pkg/appctx"
ctxpkg "github.com/owncloud/reva/v2/pkg/ctx"
"github.com/owncloud/reva/v2/pkg/errtypes"
"github.com/owncloud/reva/v2/pkg/storage"
"github.com/owncloud/reva/v2/pkg/utils"
)
const defaultFilePerm = os.FileMode(0664)
// FileSession is the Session implementation for disk-backed uploads. While an
// upload is in progress, incoming bytes are staged in a .bin file and upload
// metadata (size, owner, checksums, etc.) is persisted in a .info file. Both
// survive process restarts, allowing TUS resumption.
//
// In scope: read/write the staged .bin file, persist/load upload metadata in the .info file.
// Out of scope: TUS protocol, checksums, event publishing, postprocessing — those live in coordinatedUpload and coordinator.
type FileSession struct {
store *FileStore
info tusd.FileInfo
}
// Session is the driver-agnostic view of an upload session the Coordinator
// needs. Implementations must be pure state (CRUD): protocol orchestration
// belongs to coordinatedUpload or the coordinator itself.
type Session interface {
storage.UploadSession
// Data access — delegated to by coordinatedUpload for TUS reads/writes.
GetInfo(ctx context.Context) (tusd.FileInfo, error)
GetReader(ctx context.Context) (io.ReadCloser, error)
WriteChunk(ctx context.Context, offset int64, src io.Reader) (int64, error)
// Internal coordinator plumbing.
Chunk() string
BinPath() string
ExecutantUser() *userpb.User
ProviderID() string
SpaceID() string
NodeID() string
NodeParentID() string
NodeExists() bool
Dir() string
URL(ctx context.Context) (string, error)
SetScanData(result string, date time.Time)
Checksums() storage.UploadChecksums
SetChecksums(sha1, md5, adler32 []byte)
SizeDiff() int64
SetSizeDiff(d int64)
VersionCreated() bool
SetVersionCreated(v bool)
Metadata() map[string]string
Persist(ctx context.Context) error
Cleanup(ctx context.Context, cleanBin, cleanInfo bool)
Context(ctx context.Context) context.Context
// Typed setters used by Coordinator.InitiateUpload to populate a new session
// without knowing internal storage key names.
SetStorageValue(key, value string)
SetMetadata(key, value string)
SetSize(size int64)
SetSizeIsDeferred(value bool)
SetExecutant(u *userpb.User)
TouchBin() error
}
func (s *FileSession) GetInfo(_ context.Context) (tusd.FileInfo, error) {
return s.info, nil
}
func (s *FileSession) GetReader(_ context.Context) (io.ReadCloser, error) {
return os.Open(s.binPath())
}
func (s *FileSession) WriteChunk(ctx context.Context, offset int64, src io.Reader) (int64, error) {
file, err := os.OpenFile(s.binPath(), os.O_WRONLY|os.O_APPEND, defaultFilePerm)
if err != nil {
return 0, err
}
defer file.Close()
n, err := io.Copy(file, src)
if err != nil && err != io.ErrUnexpectedEOF {
return n, err
}
s.info.Offset += n
return n, nil
}
// Purge removes all on-disk state for this session.
func (s *FileSession) Purge(ctx context.Context) {
s.Cleanup(ctx, true, true)
}
// ScanData returns the AV scan result and scan date stored on the session.
func (s *FileSession) ScanData() (string, time.Time) {
date := s.info.MetaData["scanDate"]
if date == "" {
return "", time.Time{}
}
d, _ := time.Parse(time.RFC3339, date)
return s.info.MetaData["scanResult"], d
}
// ID returns the upload session ID.
func (s *FileSession) ID() string {
return s.info.ID
}
// Filename returns the filename stored in the session.
func (s *FileSession) Filename() string {
return s.info.Storage["NodeName"]
}
// Size returns the declared upload size.
func (s *FileSession) Size() int64 {
return s.info.Size
}
// Offset returns the current upload offset.
func (s *FileSession) Offset() int64 {
return s.info.Offset
}
// Chunk returns the chunk basename stored in the session, or "" for non-chunked uploads.
func (s *FileSession) Chunk() string {
return s.info.Storage["Chunk"]
}
// BinPath returns the path to the staged binary file.
func (s *FileSession) BinPath() string {
return s.binPath()
}
// SpaceGid returns the numeric GID of the space owner, or "" if not set.
func (s *FileSession) SpaceGid() string {
return s.info.Storage["SpaceGid"]
}
// ProviderID returns the storage provider ID stored in the session.
func (s *FileSession) ProviderID() string {
return s.info.MetaData["providerID"]
}
// SpaceID returns the space (root) ID.
func (s *FileSession) SpaceID() string {
return s.info.Storage["SpaceRoot"]
}
// NodeID returns the node ID for this upload.
func (s *FileSession) NodeID() string {
return s.info.Storage["NodeId"]
}
// NodeParentID returns the parent node ID for this upload.
func (s *FileSession) NodeParentID() string {
return s.info.Storage["NodeParentId"]
}
// NodeExists returns whether the target node existed when the upload was initiated.
func (s *FileSession) NodeExists() bool {
return s.info.Storage["NodeExists"] == "true"
}
// Dir returns the directory portion of the upload path.
func (s *FileSession) Dir() string {
return s.info.Storage["Dir"]
}
// IsProcessing returns true if all bytes are received but postprocessing has not finished.
func (s *FileSession) IsProcessing() bool {
return s.info.Size == s.info.Offset && s.info.MetaData["scanResult"] == ""
}
// SpaceOwner returns the space owner user ID.
func (s *FileSession) SpaceOwner() *userpb.UserId {
return &userpb.UserId{
OpaqueId: s.info.Storage["SpaceOwnerOrManager"],
Idp: s.info.Storage["SpaceOwnerIdp"],
Type: userpb.UserType(userpb.UserType_value[s.info.Storage["SpaceOwnerType"]]),
}
}
// Executant returns the user ID of the user who initiated this upload.
func (s *FileSession) Executant() userpb.UserId {
return userpb.UserId{
Type: utils.UserTypeMap(s.info.Storage["UserType"]),
Idp: s.info.Storage["Idp"],
OpaqueId: s.info.Storage["UserId"],
}
}
// Expires returns the upload expiry time.
func (s *FileSession) Expires() time.Time {
var t time.Time
if value, ok := s.info.MetaData["expires"]; ok {
t, _ = utils.MTimeToTime(value)
}
return t
}
// Reference returns a CS3 reference for the resource being uploaded.
func (s *FileSession) Reference() provider.Reference {
return provider.Reference{
ResourceId: &provider.ResourceId{
StorageId: s.info.MetaData["providerID"],
SpaceId: s.info.Storage["SpaceRoot"],
OpaqueId: s.info.Storage["NodeId"],
},
}
}
// Checksums returns the pre-computed checksums stored on the session.
func (s *FileSession) Checksums() storage.UploadChecksums {
decode := func(key string) []byte {
b, _ := hex.DecodeString(s.info.MetaData[key])
return b
}
return storage.UploadChecksums{
SHA1: decode("checksumSHA1"),
MD5: decode("checksumMD5"),
Adler32: decode("checksumAdler32"),
}
}
// Metadata returns the upload metadata the coordinator passes to the driver.
func (s *FileSession) Metadata() map[string]string {
return map[string]string{
"providerID": s.info.MetaData["providerID"],
"mtime": s.info.MetaData["mtime"],
"nodeExists": s.info.Storage["NodeExists"],
"sessionID": s.info.ID,
"if-match": s.info.MetaData["if-match"],
"if-none-match": s.info.MetaData["if-none-match"],
"if-unmodified-since": s.info.MetaData["if-unmodified-since"],
}
}
// SizeDiff returns the tree size change PrepareUpload propagated optimistically.
// Rolling an upload back has to undo exactly that amount.
func (s *FileSession) SizeDiff() int64 {
d, _ := strconv.ParseInt(s.info.MetaData["sizeDiff"], 10, 64)
return d
}
// SetSizeDiff records the size change PrepareUpload reported. It is persisted
// because the async path prepares and commits in different processes, so the
// value cannot be held in memory between the two.
func (s *FileSession) SetSizeDiff(d int64) {
s.info.MetaData["sizeDiff"] = strconv.FormatInt(d, 10)
}
// VersionCreated reports whether this upload superseded existing content, which
// UploadReady consumers use to tell an overwrite from a new file.
func (s *FileSession) VersionCreated() bool {
return s.info.MetaData["versionCreated"] == "true"
}
// SetVersionCreated records what PrepareUpload reported. Persisted for the same
// reason as the size diff: on the async path the commit runs in another process.
func (s *FileSession) SetVersionCreated(v bool) {
s.info.MetaData["versionCreated"] = strconv.FormatBool(v)
}
// SetScanData stores AV scan results on the session.
func (s *FileSession) SetScanData(result string, date time.Time) {
s.info.MetaData["scanResult"] = result
s.info.MetaData["scanDate"] = date.Format(time.RFC3339)
}
// SetChecksums stores pre-computed checksums so CommitUpload can use them without
// re-reading the binary file.
func (s *FileSession) SetChecksums(sha1Sum, md5Sum, adler32Sum []byte) {
s.info.MetaData["checksumSHA1"] = hex.EncodeToString(sha1Sum)
s.info.MetaData["checksumMD5"] = hex.EncodeToString(md5Sum)
s.info.MetaData["checksumAdler32"] = hex.EncodeToString(adler32Sum)
}
// SetMetadata sets a user-visible upload metadata field.
func (s *FileSession) SetMetadata(key, value string) {
s.info.MetaData[key] = value
}
// SetStorageValue sets an internal storage field on the session.
func (s *FileSession) SetStorageValue(key, value string) {
s.info.Storage[key] = value
}
// SetSize updates the declared upload size.
func (s *FileSession) SetSize(size int64) {
s.info.Size = size
}
// SetSizeIsDeferred marks the upload size as not yet known.
func (s *FileSession) SetSizeIsDeferred(value bool) {
s.info.SizeIsDeferred = value
}
// SetExecutant stores the identity of the user who initiated the upload.
func (s *FileSession) SetExecutant(u *userpb.User) {
s.info.Storage["Idp"] = u.GetId().GetIdp()
s.info.Storage["UserId"] = u.GetId().GetOpaqueId()
s.info.Storage["UserType"] = utils.UserTypeToString(u.GetId().Type)
s.info.Storage["UserName"] = u.GetUsername()
s.info.Storage["UserDisplayName"] = u.GetDisplayName()
b, _ := json.Marshal(u.GetOpaque())
s.info.Storage["UserOpaque"] = string(b)
g, _ := json.Marshal(u.GetGroups())
s.info.Storage["UserGroups"] = string(g)
}
// TouchBin creates the empty staging file.
func (s *FileSession) TouchBin() error {
f, err := os.OpenFile(s.binPath(), os.O_CREATE|os.O_WRONLY, defaultFilePerm)
if err != nil {
return err
}
return f.Close()
}
// Persist writes the session metadata atomically to disk.
func (s *FileSession) Persist(ctx context.Context) error {
infoPath := s.infoPath()
if err := os.MkdirAll(filepath.Dir(infoPath), 0700); err != nil {
return err
}
d, err := json.Marshal(s.info)
if err != nil {
return err
}
return renameio.WriteFile(infoPath, d, 0600)
}
// Cleanup removes the staged binary and/or info file.
// Node deletion and processing flag changes are the coordinator's responsibility.
func (s *FileSession) Cleanup(ctx context.Context, cleanBin, cleanInfo bool) {
if cleanBin {
if err := os.Remove(s.binPath()); err != nil && !errors.Is(err, os.ErrNotExist) {
appctx.GetLogger(ctx).Error().Str("path", s.binPath()).Err(err).Msg("filestore: removing staged binary failed")
}
}
if cleanInfo {
if err := os.Remove(s.infoPath()); err != nil && !errors.Is(err, os.ErrNotExist) {
appctx.GetLogger(ctx).Error().Str("path", s.infoPath()).Err(err).Msg("filestore: removing session info failed")
}
}
}
// Context reconstructs a context carrying the user, logger, lock ID, and
// initiator ID that were recorded when the upload was initiated.
func (s *FileSession) Context(ctx context.Context) context.Context {
sub := s.store.log.With().Int("pid", os.Getpid()).Logger()
ctx = appctx.WithLogger(ctx, &sub)
ctx = ctxpkg.ContextSetLockID(ctx, s.info.MetaData["lockid"])
ctx = ctxpkg.ContextSetUser(ctx, s.ExecutantUser())
return ctxpkg.ContextSetInitiator(ctx, s.info.MetaData["initiatorid"])
}
// URL returns a signed JWT URL that the postprocessing service can use to
// download the staged binary via the data gateway.
func (s *FileSession) URL(_ context.Context) (string, error) {
type transferClaims struct {
jwt.RegisteredClaims
Target string `json:"target"`
}
target := joinURLParts(s.store.opts.DownloadEndpoint, "tus/", s.info.ID)
ttl := time.Duration(s.store.opts.TransferExpires) * time.Second
claims := transferClaims{
RegisteredClaims: jwt.RegisteredClaims{
ExpiresAt: jwt.NewNumericDate(time.Now().Add(ttl)),
Audience: jwt.ClaimStrings{"reva"},
IssuedAt: jwt.NewNumericDate(time.Now()),
},
Target: target,
}
t := jwt.NewWithClaims(jwt.GetSigningMethod("HS256"), claims)
tkn, err := t.SignedString([]byte(s.store.opts.TransferSharedSecret))
if err != nil {
return "", errors.Wrapf(err, "filestore: error signing transfer token with claims %+v", claims)
}
return joinURLParts(s.store.opts.DataGatewayEndpoint, tkn), nil
}
func (s *FileSession) ToFileInfo() tusd.FileInfo {
return s.info
}
func (s *FileSession) InitiatorID() string {
return s.info.MetaData["initiatorid"]
}
func (s *FileSession) binPath() string {
return filepath.Join(s.store.uploadDir, s.info.ID)
}
func (s *FileSession) infoPath() string {
return fileSessionPath(s.store.uploadDir, s.info.ID)
}
// ExecutantUser returns the full identity of the user who initiated the upload.
// Upload events must carry it rather than the bare id from Executant(): consumers
// read the display name straight off the event and do not look it up, so an
// id-only user reaches the activity feed with a blank name.
func (s *FileSession) ExecutantUser() *userpb.User {
var o *typespb.Opaque
_ = json.Unmarshal([]byte(s.info.Storage["UserOpaque"]), &o)
var groups []string
_ = json.Unmarshal([]byte(s.info.Storage["UserGroups"]), &groups)
return &userpb.User{
Id: &userpb.UserId{
Type: utils.UserTypeMap(s.info.Storage["UserType"]),
Idp: s.info.Storage["Idp"],
OpaqueId: s.info.Storage["UserId"],
},
Username: s.info.Storage["UserName"],
DisplayName: s.info.Storage["UserDisplayName"],
Opaque: o,
Groups: groups,
}
}
// fileSessionPath returns the path to the .info file for the given session ID.
func fileSessionPath(uploadDir, id string) string {
return filepath.Join(uploadDir, id+".info")
}
// calculateChecksums computes sha1, md5, and adler32 in a single pass over path.
func calculateChecksums(_ context.Context, path string) (hash.Hash, hash.Hash, hash.Hash32, error) {
sha1h := sha1.New() //nolint:gosec
md5h := md5.New() //nolint:gosec
adler32h := adler32.New()
f, err := os.Open(path)
if err != nil {
return nil, nil, nil, err
}
defer f.Close()
r1 := io.TeeReader(f, sha1h)
r2 := io.TeeReader(r1, md5h)
if _, err = io.Copy(adler32h, r2); err != nil {
return nil, nil, nil, err
}
return sha1h, md5h, adler32h, nil
}
func checkHash(expected string, h hash.Hash) error {
got := hex.EncodeToString(h.Sum(nil))
if expected != got {
return errtypes.ChecksumMismatch(fmt.Sprintf("invalid checksum: expected %s got %s", expected, got))
}
return nil
}
// joinURLParts concatenates URL path segments, inserting "/" between them if needed.
func joinURLParts(parts ...string) string {
var b strings.Builder
for i, p := range parts {
b.WriteString(p)
if i < len(parts)-1 && !strings.HasSuffix(p, "/") {
b.WriteByte('/')
}
}
return b.String()
}
+151
View File
@@ -0,0 +1,151 @@
package upload
import (
"context"
"fmt"
"io"
"net/http"
"os"
tusd "github.com/tus/tusd/v2/pkg/handler"
"github.com/owncloud/reva/v2/pkg/appctx"
"github.com/owncloud/reva/v2/pkg/errtypes"
)
var errNotImplemented = tusd.NewError("ERR_NOT_IMPLEMENTED", "use InitiateUpload on the CS3 API to start a new upload", http.StatusNotImplemented)
// tusAdapter adapts a single upload session to tusd's Upload interfaces.
type tusAdapter struct {
session Session
coord *coordinator
}
func (u *tusAdapter) GetInfo(ctx context.Context) (tusd.FileInfo, error) {
return u.session.GetInfo(ctx)
}
func (u *tusAdapter) GetReader(ctx context.Context) (io.ReadCloser, error) {
return u.session.GetReader(ctx)
}
func (u *tusAdapter) WriteChunk(ctx context.Context, offset int64, src io.Reader) (int64, error) {
return u.session.WriteChunk(ctx, offset, src)
}
// FinishUpload runs the coordinator's finish path once all bytes have arrived.
func (u *tusAdapter) FinishUpload(ctx context.Context) error {
_, err := u.coord.finishUpload(u.session.Context(ctx), u.session)
// tusd answers an error type it does not recognise with a bare 500.
switch err.(type) {
case nil:
return nil
case errtypes.AlreadyExists:
return tusd.NewError("ERR_ALREADY_EXISTS", err.Error(), http.StatusConflict)
case errtypes.ResourceProcessing, errtypes.TooEarly:
return tusd.NewError("ERR_TOO_EARLY", err.Error(), http.StatusTooEarly)
case errtypes.Aborted:
return tusd.NewError("ERR_PRECONDITION_FAILED", err.Error(), http.StatusPreconditionFailed)
case errtypes.PreconditionFailed:
return tusd.NewError("ERR_PRECONDITION_FAILED", err.Error(), http.StatusMethodNotAllowed)
case errtypes.Locked:
return tusd.NewError("ERR_LOCKED", err.Error(), http.StatusLocked)
case errtypes.BadRequest:
return tusd.NewError("ERR_BAD_REQUEST", err.Error(), http.StatusBadRequest)
case errtypes.ChecksumMismatch:
return tusd.NewError("ERR_CHECKSUM_MISMATCH", err.Error(), errtypes.StatusChecksumMismatch)
case errtypes.IsPermissionDenied:
return tusd.NewError("ERR_PERMISSION_DENIED", err.Error(), http.StatusForbidden)
default:
return err
}
}
// Terminate discards an upload, so a cancelled one leaves nothing behind.
func (u *tusAdapter) Terminate(ctx context.Context) error {
ref := u.session.Reference()
// Rollback rather than Delete, which is permission-gated. It is a no-op unless
// this upload still owns the node.
if err := u.coord.fs.RollbackUpload(ctx, &ref, u.session.ID(), rollbackInfo(u.session, u.session.SizeDiff())); err != nil {
appctx.GetLogger(ctx).Error().Err(err).Str("uploadid", u.session.ID()).Msg("could not roll back terminated upload, keeping session")
return err
}
// A node that was never created cannot be unmarked, which is the normal case here.
if err := u.coord.fs.MarkProcessing(ctx, &ref, false, u.session.ID()); err != nil {
appctx.GetLogger(ctx).Debug().Err(err).Str("uploadid", u.session.ID()).Msg("could not unmark terminated upload")
}
u.session.Cleanup(ctx, true, true)
return nil
}
// DeclareLength records the total size for uploads initiated without one.
func (u *tusAdapter) DeclareLength(ctx context.Context, length int64) error {
u.session.SetSize(length)
u.session.SetSizeIsDeferred(false)
return u.session.Persist(ctx)
}
// ConcatUploads appends the staged bytes of the partial uploads, in the order given.
func (u *tusAdapter) ConcatUploads(ctx context.Context, partials []tusd.Upload) error {
file, err := os.OpenFile(u.session.BinPath(), os.O_WRONLY|os.O_APPEND, defaultFilePerm)
if err != nil {
return err
}
defer file.Close()
for _, partial := range partials {
p, ok := partial.(*tusAdapter)
if !ok {
return fmt.Errorf("coordinator: unexpected partial upload type %T", partial)
}
src, err := p.session.GetReader(ctx)
if err != nil {
return err
}
_, copyErr := io.Copy(file, src)
src.Close()
if copyErr != nil {
return copyErr
}
}
return nil
}
// UseIn registers the coordinator as tusd's data store, in place of the driver's own.
func (c *coordinator) UseIn(composer *tusd.StoreComposer) {
composer.UseCore(c)
composer.UseTerminater(c)
composer.UseConcater(c)
composer.UseLengthDeferrer(c)
}
// NewUpload is unsupported: uploads always start through the CS3 InitiateUpload call.
func (c *coordinator) NewUpload(_ context.Context, _ tusd.FileInfo) (tusd.Upload, error) {
return nil, errNotImplemented
}
// GetUpload wraps the session with the given id for the TUS data path.
func (c *coordinator) GetUpload(ctx context.Context, id string) (tusd.Upload, error) {
session, err := c.store.Get(ctx, id)
if err != nil {
return nil, err
}
return &tusAdapter{session: session, coord: c}, nil
}
// The As* methods let tusd reach the extension interfaces on a plain tusd.Upload.
func (c *coordinator) AsTerminatableUpload(up tusd.Upload) tusd.TerminatableUpload {
return up.(*tusAdapter)
}
func (c *coordinator) AsLengthDeclarableUpload(up tusd.Upload) tusd.LengthDeclarableUpload {
return up.(*tusAdapter)
}
func (c *coordinator) AsConcatableUpload(up tusd.Upload) tusd.ConcatableUpload {
return up.(*tusAdapter)
}
+41
View File
@@ -10,6 +10,7 @@ import (
"go/token"
"iter"
"reflect"
"strings"
"golang.org/x/tools/go/ast/edge"
)
@@ -110,6 +111,46 @@ func (c Cursor) String() string {
return reflect.TypeOf(c.Node()).String()
}
// GoString returns a string describing the cursor's path from the
// root, if any.
func (c Cursor) GoString() string {
if !c.Valid() {
return "(invalid)"
}
if c.index < 0 {
return "(root)"
}
// e.g "File.Decls[1].(*ast.GenDecl).Specs[0].(*ast.TypeSpec)"
//
// In hindsight even the File node should have reported a
// virtual ParentEdge of (Root_Files, i) where i is the index
// among the files passed to NewInspector. Then the path would
// read "(root).Files[i]", etc; but we missed the boat.
var buf strings.Builder
buf.WriteString("File")
var visit func(Cursor)
visit = func(c Cursor) {
ek, idx := c.ParentEdge()
if ek == edge.Invalid {
return // File
}
visit(c.Parent())
fmt.Fprintf(&buf, ".%s", ek.FieldName())
if idx >= 0 {
fmt.Fprintf(&buf, "[%d]", idx)
}
ftype := ek.FieldType()
if idx >= 0 {
ftype = ftype.Elem() // []T -> T
}
if ftype.Kind() == reflect.Interface {
fmt.Fprintf(&buf, ".(%T)", c.Node())
}
}
visit(c)
return buf.String()
}
// indices return the [start, end) half-open interval of event indices.
func (c Cursor) indices() (int32, int32) {
if c.index < 0 {
+4 -29
View File
@@ -5,11 +5,11 @@
package packages
import (
"cmp"
"fmt"
"iter"
"os"
"slices"
"golang.org/x/tools/internal/moremaps"
)
// Visit visits all the packages in the import graph whose roots are
@@ -40,7 +40,7 @@ func Visit(pkgs []*Package, pre func(*Package) bool, post func(*Package)) {
seen[pkg] = true
if pre == nil || pre(pkg) {
for _, imp := range sorted(pkg.Imports) { // for determinism
for _, imp := range moremaps.Sorted(pkg.Imports) { // for determinism
visit(imp)
}
}
@@ -88,7 +88,7 @@ func Postorder(pkgs []*Package) iter.Seq[*Package] {
visit = func(pkg *Package) bool {
if !seen[pkg] {
seen[pkg] = true
for _, imp := range sorted(pkg.Imports) { // for determinism
for _, imp := range moremaps.Sorted(pkg.Imports) { // for determinism
if !visit(imp) {
return false
}
@@ -106,28 +106,3 @@ func Postorder(pkgs []*Package) iter.Seq[*Package] {
}
}
}
// -- copied from golang.org.x/tools/gopls/internal/util/moremaps --
// sorted returns an iterator over the entries of m in key order.
func sorted[M ~map[K]V, K cmp.Ordered, V any](m M) iter.Seq2[K, V] {
// TODO(adonovan): use maps.Sorted if proposal #68598 is accepted.
return func(yield func(K, V) bool) {
keys := keySlice(m)
slices.Sort(keys)
for _, k := range keys {
if !yield(k, m[k]) {
break
}
}
}
}
// KeySlice returns the keys of the map M, like slices.Collect(maps.Keys(m)).
func keySlice[M ~map[K]V, K comparable, V any](m M) []K {
r := make([]K, 0, len(m))
for k := range m {
r = append(r, k)
}
return r
}
-86
View File
@@ -1,86 +0,0 @@
// Copyright 2018 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 typeutil
import (
"go/ast"
"go/types"
_ "unsafe" // for linkname
)
// Callee returns the named target of a function call, if any:
// a function, method, builtin, or variable.
// It returns nil for a T(x) conversion.
//
// Functions and methods may potentially have type parameters.
//
// Note: for calls of instantiated functions and methods, Callee returns
// the corresponding generic function or method on the generic type.
func Callee(info *types.Info, call *ast.CallExpr) types.Object {
obj := info.Uses[usedIdent(info, call.Fun)]
if obj == nil {
return nil
}
if _, ok := obj.(*types.TypeName); ok {
return nil
}
return obj
}
// StaticCallee returns the target (function or method) of a static function
// call, if any. It returns nil for calls to builtins.
//
// Note: for calls of instantiated functions and methods, StaticCallee returns
// the corresponding generic function or method on the generic type.
func StaticCallee(info *types.Info, call *ast.CallExpr) *types.Func {
obj := info.Uses[usedIdent(info, call.Fun)]
fn, _ := obj.(*types.Func)
if fn == nil || interfaceMethod(fn) {
return nil
}
return fn
}
// usedIdent is the implementation of [internal/typesinternal.UsedIdent].
// It returns the identifier associated with e.
// See typesinternal.UsedIdent for a fuller description.
// This function should live in typesinternal, but cannot because it would
// create an import cycle.
//
//go:linkname usedIdent golang.org/x/tools/go/types/typeutil.usedIdent
func usedIdent(info *types.Info, e ast.Expr) *ast.Ident {
if info.Types == nil || info.Uses == nil {
panic("one of info.Types or info.Uses is nil; both must be populated")
}
// Look through type instantiation if necessary.
switch d := ast.Unparen(e).(type) {
case *ast.IndexExpr:
if info.Types[d.Index].IsType() {
e = d.X
}
case *ast.IndexListExpr:
e = d.X
}
switch e := ast.Unparen(e).(type) {
// info.Uses always has the object we want, even for selector expressions.
// We don't need info.Selections.
// See go/types/recording.go:recordSelection.
case *ast.Ident:
return e
case *ast.SelectorExpr:
return e.Sel
}
return nil
}
// interfaceMethod reports whether its argument is a method of an interface.
// This function should live in typesinternal, but cannot because it would create an import cycle.
//
//go:linkname interfaceMethod golang.org/x/tools/go/types/typeutil.interfaceMethod
func interfaceMethod(f *types.Func) bool {
recv := f.Signature().Recv()
return recv != nil && types.IsInterface(recv.Type())
}
-30
View File
@@ -1,30 +0,0 @@
// Copyright 2014 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 typeutil
import "go/types"
// Dependencies returns all dependencies of the specified packages.
//
// Dependent packages appear in topological order: if package P imports
// package Q, Q appears earlier than P in the result.
// The algorithm follows import statements in the order they
// appear in the source code, so the result is a total order.
func Dependencies(pkgs ...*types.Package) []*types.Package {
var result []*types.Package
seen := make(map[*types.Package]bool)
var visit func(pkgs []*types.Package)
visit = func(pkgs []*types.Package) {
for _, p := range pkgs {
if !seen[p] {
seen[p] = true
visit(p.Imports())
result = append(result, p)
}
}
}
visit(pkgs)
return result
}
-459
View File
@@ -1,459 +0,0 @@
// Copyright 2014 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 typeutil defines various utilities for types, such as [Map],
// a hash table that maps [types.Type] to any value.
package typeutil
import (
"bytes"
"fmt"
"go/types"
"hash/maphash"
"golang.org/x/tools/internal/typeparams"
)
// Map is a hash-table-based mapping from types (types.Type) to
// arbitrary values. The concrete types that implement
// the Type interface are pointers. Since they are not canonicalized,
// == cannot be used to check for equivalence, and thus we cannot
// simply use a Go map.
//
// Just as with map[K]V, a nil *Map is a valid empty map.
//
// Read-only map operations ([Map.At], [Map.Len], and so on) may
// safely be called concurrently.
//
// TODO(adonovan): deprecate in favor of https://go.dev/issues/69420
// and 69559, if the latter proposals for a generic hash-map type and
// a types.Hash function are accepted.
type Map struct {
table map[uint32][]entry // maps hash to bucket; entry.key==nil means unused
length int // number of map entries
}
// entry is an entry (key/value association) in a hash bucket.
type entry struct {
key types.Type
value any
}
// SetHasher has no effect.
//
// It is a relic of an optimization that is no longer profitable. Do
// not use [Hasher], [MakeHasher], or [SetHasher] in new code.
func (m *Map) SetHasher(Hasher) {}
// Delete removes the entry with the given key, if any.
// It returns true if the entry was found.
func (m *Map) Delete(key types.Type) bool {
if m != nil && m.table != nil {
hash := hash(key)
bucket := m.table[hash]
for i, e := range bucket {
if e.key != nil && types.Identical(key, e.key) {
// We can't compact the bucket as it
// would disturb iterators.
bucket[i] = entry{}
m.length--
return true
}
}
}
return false
}
// At returns the map entry for the given key.
// The result is nil if the entry is not present.
func (m *Map) At(key types.Type) any {
if m != nil && m.table != nil {
for _, e := range m.table[hash(key)] {
if e.key != nil && types.Identical(key, e.key) {
return e.value
}
}
}
return nil
}
// Set sets the map entry for key to val,
// and returns the previous entry, if any.
func (m *Map) Set(key types.Type, value any) (prev any) {
if m.table != nil {
hash := hash(key)
bucket := m.table[hash]
var hole *entry
for i, e := range bucket {
if e.key == nil {
hole = &bucket[i]
} else if types.Identical(key, e.key) {
prev = e.value
bucket[i].value = value
return
}
}
if hole != nil {
*hole = entry{key, value} // overwrite deleted entry
} else {
m.table[hash] = append(bucket, entry{key, value})
}
} else {
hash := hash(key)
m.table = map[uint32][]entry{hash: {entry{key, value}}}
}
m.length++
return
}
// Len returns the number of map entries.
func (m *Map) Len() int {
if m != nil {
return m.length
}
return 0
}
// Iterate calls function f on each entry in the map in unspecified order.
//
// If f should mutate the map, Iterate provides the same guarantees as
// Go maps: if f deletes a map entry that Iterate has not yet reached,
// f will not be invoked for it, but if f inserts a map entry that
// Iterate has not yet reached, whether or not f will be invoked for
// it is unspecified.
func (m *Map) Iterate(f func(key types.Type, value any)) {
if m != nil {
for _, bucket := range m.table {
for _, e := range bucket {
if e.key != nil {
f(e.key, e.value)
}
}
}
}
}
// Keys returns a new slice containing the set of map keys.
// The order is unspecified.
func (m *Map) Keys() []types.Type {
keys := make([]types.Type, 0, m.Len())
m.Iterate(func(key types.Type, _ any) {
keys = append(keys, key)
})
return keys
}
func (m *Map) toString(values bool) string {
if m == nil {
return "{}"
}
var buf bytes.Buffer
fmt.Fprint(&buf, "{")
sep := ""
m.Iterate(func(key types.Type, value any) {
fmt.Fprint(&buf, sep)
sep = ", "
fmt.Fprint(&buf, key)
if values {
fmt.Fprintf(&buf, ": %q", value)
}
})
fmt.Fprint(&buf, "}")
return buf.String()
}
// String returns a string representation of the map's entries.
// Values are printed using fmt.Sprintf("%v", v).
// Order is unspecified.
func (m *Map) String() string {
return m.toString(true)
}
// KeysString returns a string representation of the map's key set.
// Order is unspecified.
func (m *Map) KeysString() string {
return m.toString(false)
}
// -- Hasher --
// hash returns the hash of type t.
// TODO(adonovan): replace by types.Hash when Go proposal #69420 is accepted.
func hash(t types.Type) uint32 {
return theHasher.Hash(t)
}
// A Hasher provides a [Hasher.Hash] method to map a type to its hash value.
// Hashers are stateless, and all are equivalent.
type Hasher struct{}
var theHasher Hasher
// MakeHasher returns Hasher{}.
// Hashers are stateless; all are equivalent.
func MakeHasher() Hasher { return theHasher }
// Hash computes a hash value for the given type t such that
// Identical(t, t') => Hash(t) == Hash(t').
func (h Hasher) Hash(t types.Type) uint32 {
return hasher{inGenericSig: false}.hash(t)
}
// hasher holds the state of a single Hash traversal: whether we are
// inside the signature of a generic function; this is used to
// optimize [hasher.hashTypeParam].
type hasher struct{ inGenericSig bool }
// hashString computes the Fowler–Noll–Vo hash of s.
func hashString(s string) uint32 {
var h uint32
for i := 0; i < len(s); i++ {
h ^= uint32(s[i])
h *= 16777619
}
return h
}
// hash computes the hash of t.
func (h hasher) hash(t types.Type) uint32 {
// See Identical for rationale.
switch t := t.(type) {
case *types.Basic:
return uint32(t.Kind())
case *types.Alias:
return h.hash(types.Unalias(t))
case *types.Array:
return 9043 + 2*uint32(t.Len()) + 3*h.hash(t.Elem())
case *types.Slice:
return 9049 + 2*h.hash(t.Elem())
case *types.Struct:
var hash uint32 = 9059
for i, n := 0, t.NumFields(); i < n; i++ {
f := t.Field(i)
if f.Anonymous() {
hash += 8861
}
hash += hashString(t.Tag(i))
hash += hashString(f.Name()) // (ignore f.Pkg)
hash += h.hash(f.Type())
}
return hash
case *types.Pointer:
return 9067 + 2*h.hash(t.Elem())
case *types.Signature:
var hash uint32 = 9091
if t.Variadic() {
hash *= 8863
}
tparams := t.TypeParams()
if n := tparams.Len(); n > 0 {
h.inGenericSig = true // affects constraints, params, and results
for i := range n {
tparam := tparams.At(i)
hash += 7 * h.hash(tparam.Constraint())
}
}
return hash + 3*h.hashTuple(t.Params()) + 5*h.hashTuple(t.Results())
case *types.Union:
return h.hashUnion(t)
case *types.Interface:
// Interfaces are identical if they have the same set of methods, with
// identical names and types, and they have the same set of type
// restrictions. See go/types.identical for more details.
var hash uint32 = 9103
// Hash methods.
for i, n := 0, t.NumMethods(); i < n; i++ {
// Method order is not significant.
// Ignore m.Pkg().
m := t.Method(i)
// Use shallow hash on method signature to
// avoid anonymous interface cycles.
hash += 3*hashString(m.Name()) + 5*h.shallowHash(m.Type())
}
// Hash type restrictions.
terms, err := typeparams.InterfaceTermSet(t)
// if err != nil t has invalid type restrictions.
if err == nil {
hash += h.hashTermSet(terms)
}
return hash
case *types.Map:
return 9109 + 2*h.hash(t.Key()) + 3*h.hash(t.Elem())
case *types.Chan:
return 9127 + 2*uint32(t.Dir()) + 3*h.hash(t.Elem())
case *types.Named:
hash := h.hashTypeName(t.Obj())
targs := t.TypeArgs()
for targ := range targs.Types() {
hash += 2 * h.hash(targ)
}
return hash
case *types.TypeParam:
return h.hashTypeParam(t)
case *types.Tuple:
return h.hashTuple(t)
}
panic(fmt.Sprintf("%T: %v", t, t))
}
func (h hasher) hashTuple(tuple *types.Tuple) uint32 {
// See go/types.identicalTypes for rationale.
n := tuple.Len()
hash := 9137 + 2*uint32(n)
for i := range n {
hash += 3 * h.hash(tuple.At(i).Type())
}
return hash
}
func (h hasher) hashUnion(t *types.Union) uint32 {
// Hash type restrictions.
terms, err := typeparams.UnionTermSet(t)
// if err != nil t has invalid type restrictions. Fall back on a non-zero
// hash.
if err != nil {
return 9151
}
return h.hashTermSet(terms)
}
func (h hasher) hashTermSet(terms []*types.Term) uint32 {
hash := 9157 + 2*uint32(len(terms))
for _, term := range terms {
// term order is not significant.
termHash := h.hash(term.Type())
if term.Tilde() {
termHash *= 9161
}
hash += 3 * termHash
}
return hash
}
// hashTypeParam returns the hash of a type parameter.
func (h hasher) hashTypeParam(t *types.TypeParam) uint32 {
// Within the signature of a generic function, TypeParams are
// identical if they have the same index and constraint, so we
// hash them based on index.
//
// When we are outside a generic function, free TypeParams are
// identical iff they are the same object, so we can use a
// more discriminating hash consistent with object identity.
// This optimization saves [Map] about 4% when hashing all the
// types.Info.Types in the forward closure of net/http.
if !h.inGenericSig {
// Optimization: outside a generic function signature,
// use a more discrimating hash consistent with object identity.
return h.hashTypeName(t.Obj())
}
return 9173 + 3*uint32(t.Index())
}
var theSeed = maphash.MakeSeed()
// hashTypeName hashes the pointer of tname.
func (hasher) hashTypeName(tname *types.TypeName) uint32 {
// Since types.Identical uses == to compare TypeNames,
// the Hash function uses maphash.Comparable.
hash := maphash.Comparable(theSeed, tname)
return uint32(hash ^ (hash >> 32))
}
// shallowHash computes a hash of t without looking at any of its
// element Types, to avoid potential anonymous cycles in the types of
// interface methods.
//
// When an unnamed non-empty interface type appears anywhere among the
// arguments or results of an interface method, there is a potential
// for endless recursion. Consider:
//
// type X interface { m() []*interface { X } }
//
// The problem is that the Methods of the interface in m's result type
// include m itself; there is no mention of the named type X that
// might help us break the cycle.
// (See comment in go/types.identical, case *Interface, for more.)
func (h hasher) shallowHash(t types.Type) uint32 {
// t is the type of an interface method (Signature),
// its params or results (Tuples), or their immediate
// elements (mostly Slice, Pointer, Basic, Named),
// so there's no need to optimize anything else.
switch t := t.(type) {
case *types.Alias:
return h.shallowHash(types.Unalias(t))
case *types.Signature:
var hash uint32 = 604171
if t.Variadic() {
hash *= 971767
}
// The Signature/Tuple recursion is always finite
// and invariably shallow.
return hash + 1062599*h.shallowHash(t.Params()) + 1282529*h.shallowHash(t.Results())
case *types.Tuple:
n := t.Len()
hash := 9137 + 2*uint32(n)
for i := range n {
hash += 53471161 * h.shallowHash(t.At(i).Type())
}
return hash
case *types.Basic:
return 45212177 * uint32(t.Kind())
case *types.Array:
return 1524181 + 2*uint32(t.Len())
case *types.Slice:
return 2690201
case *types.Struct:
return 3326489
case *types.Pointer:
return 4393139
case *types.Union:
return 562448657
case *types.Interface:
return 2124679 // no recursion here
case *types.Map:
return 9109
case *types.Chan:
return 9127
case *types.Named:
return h.hashTypeName(t.Obj())
case *types.TypeParam:
return h.hashTypeParam(t)
}
panic(fmt.Sprintf("shallowHash: %T: %v", t, t))
}
-71
View File
@@ -1,71 +0,0 @@
// Copyright 2014 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.
// This file implements a cache of method sets.
package typeutil
import (
"go/types"
"sync"
)
// A MethodSetCache records the method set of each type T for which
// MethodSet(T) is called so that repeat queries are fast.
// The zero value is a ready-to-use cache instance.
type MethodSetCache struct {
mu sync.Mutex
named map[*types.Named]struct{ value, pointer *types.MethodSet } // method sets for named N and *N
others map[types.Type]*types.MethodSet // all other types
}
// MethodSet returns the method set of type T. It is thread-safe.
//
// If cache is nil, this function is equivalent to types.NewMethodSet(T).
// Utility functions can thus expose an optional *MethodSetCache
// parameter to clients that care about performance.
func (cache *MethodSetCache) MethodSet(T types.Type) *types.MethodSet {
if cache == nil {
return types.NewMethodSet(T)
}
cache.mu.Lock()
defer cache.mu.Unlock()
switch T := types.Unalias(T).(type) {
case *types.Named:
return cache.lookupNamed(T).value
case *types.Pointer:
if N, ok := types.Unalias(T.Elem()).(*types.Named); ok {
return cache.lookupNamed(N).pointer
}
}
// all other types
// (The map uses pointer equivalence, not type identity.)
mset := cache.others[T]
if mset == nil {
mset = types.NewMethodSet(T)
if cache.others == nil {
cache.others = make(map[types.Type]*types.MethodSet)
}
cache.others[T] = mset
}
return mset
}
func (cache *MethodSetCache) lookupNamed(named *types.Named) struct{ value, pointer *types.MethodSet } {
if cache.named == nil {
cache.named = make(map[*types.Named]struct{ value, pointer *types.MethodSet })
}
// Avoid recomputing mset(*T) for each distinct Pointer
// instance whose underlying type is a named type.
msets, ok := cache.named[named]
if !ok {
msets.value = types.NewMethodSet(named)
msets.pointer = types.NewMethodSet(types.NewPointer(named))
cache.named[named] = msets
}
return msets
}
-53
View File
@@ -1,53 +0,0 @@
// Copyright 2014 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 typeutil
// This file defines utilities for user interfaces that display types.
import (
"go/types"
)
// IntuitiveMethodSet returns the intuitive method set of a type T,
// which is the set of methods you can call on an addressable value of
// that type.
//
// The result always contains MethodSet(T), and is exactly MethodSet(T)
// for interface types and for pointer-to-concrete types.
// For all other concrete types T, the result additionally
// contains each method belonging to *T if there is no identically
// named method on T itself.
//
// This corresponds to user intuition about method sets;
// this function is intended only for user interfaces.
//
// The order of the result is as for types.MethodSet(T).
func IntuitiveMethodSet(T types.Type, msets *MethodSetCache) []*types.Selection {
isPointerToConcrete := func(T types.Type) bool {
ptr, ok := types.Unalias(T).(*types.Pointer)
return ok && !types.IsInterface(ptr.Elem())
}
var result []*types.Selection
mset := msets.MethodSet(T)
if types.IsInterface(T) || isPointerToConcrete(T) {
for i, n := 0, mset.Len(); i < n; i++ {
result = append(result, mset.At(i))
}
} else {
// T is some other concrete type.
// Report methods of T and *T, preferring those of T.
pmset := msets.MethodSet(types.NewPointer(T))
for i, n := 0, pmset.Len(); i < n; i++ {
meth := pmset.At(i)
if m := mset.Lookup(meth.Obj().Pkg(), meth.Obj().Name()); m != nil {
meth = m
}
result = append(result, meth)
}
}
return result
}
+116
View File
@@ -0,0 +1,116 @@
// Copyright 2023 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 moremaps contains more functions for working with maps.
package moremaps
import (
"cmp"
"iter"
"maps"
"slices"
)
// Arbitrary returns an arbitrary (key, value) entry from the map and ok is true, if
// the map is not empty. Otherwise, it returns zero values for K and V, and false.
func Arbitrary[K comparable, V any](m map[K]V) (_ K, _ V, ok bool) {
for k, v := range m {
return k, v, true
}
return
}
// Group returns a new non-nil map containing the elements of s grouped by the
// keys returned from the key func.
func Group[K comparable, V any](s []V, key func(V) K) map[K][]V {
m := make(map[K][]V)
for _, v := range s {
k := key(v)
m[k] = append(m[k], v)
}
return m
}
// KeySlice returns the keys of the map M, like slices.Collect(maps.Keys(m)).
func KeySlice[M ~map[K]V, K comparable, V any](m M) []K {
r := make([]K, 0, len(m))
for k := range m {
r = append(r, k)
}
return r
}
// ValueSlice returns the values of the map M, like slices.Collect(maps.Values(m)).
func ValueSlice[M ~map[K]V, K comparable, V any](m M) []V {
r := make([]V, 0, len(m))
for _, v := range m {
r = append(r, v)
}
return r
}
// SameKeys reports whether x and y have equal sets of keys.
func SameKeys[K comparable, V1, V2 any](x map[K]V1, y map[K]V2) bool {
ignoreValues := func(V1, V2) bool { return true }
return maps.EqualFunc(x, y, ignoreValues)
}
// Sorted returns an iterator over the entries of m in key order.
func Sorted[M ~map[K]V, K cmp.Ordered, V any](m M) iter.Seq2[K, V] {
// TODO(adonovan): use maps.Sorted if proposal #68598 is accepted.
return func(yield func(K, V) bool) {
keys := KeySlice(m)
slices.Sort(keys)
for _, k := range keys {
if !yield(k, m[k]) {
break
}
}
}
}
// SortedFunc returns an iterator over the entries of m in the key order determined by cmp.
func SortedFunc[M ~map[K]V, K comparable, V any](m M, cmp func(x, y K) int) iter.Seq2[K, V] {
// TODO(adonovan): use maps.SortedFunc if proposal #68598 is accepted.
return func(yield func(K, V) bool) {
keys := KeySlice(m)
slices.SortFunc(keys, cmp)
for _, k := range keys {
if !yield(k, m[k]) {
break
}
}
}
}
// Delete is like delete(m, k) but reports whether deletion occurred.
func Delete[M ~map[K]V, K comparable, V any](m M, k K) bool {
pre := len(m)
delete(m, k)
return pre != len(m)
}
// Entry is a key-value pair obtained from a map.
type Entry[K comparable, V any] struct {
Key K
Value V
}
// Entries returns a new unordered array of the entries of a map.
func Entries[M ~map[K]V, K comparable, V any](m M) []Entry[K, V] {
entries := make([]Entry[K, V], 0, len(m))
for k, v := range m {
entries = append(entries, Entry[K, V]{k, v})
}
return entries
}
// FromEntries returns a new map into which the entries have been inserted in order.
func FromEntries[K comparable, V any](entries []Entry[K, V]) map[K]V {
m := make(map[K]V, len(entries))
for _, e := range entries {
m[e.Key] = e.Value
}
return m
}
-68
View File
@@ -1,68 +0,0 @@
// Copyright 2021 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 typeparams contains common utilities for writing tools that
// interact with generic Go code, as introduced with Go 1.18. It
// supplements the standard library APIs. Notably, the StructuralTerms
// API computes a minimal representation of the structural
// restrictions on a type parameter.
//
// An external version of these APIs is available in the
// golang.org/x/exp/typeparams module.
package typeparams
import (
"go/ast"
"go/token"
"go/types"
)
// UnpackIndexExpr extracts data from AST nodes that represent index
// expressions.
//
// For an ast.IndexExpr, the resulting indices slice will contain exactly one
// index expression. For an ast.IndexListExpr (go1.18+), it may have a variable
// number of index expressions.
//
// For nodes that don't represent index expressions, the first return value of
// UnpackIndexExpr will be nil.
func UnpackIndexExpr(n ast.Node) (x ast.Expr, lbrack token.Pos, indices []ast.Expr, rbrack token.Pos) {
switch e := n.(type) {
case *ast.IndexExpr:
return e.X, e.Lbrack, []ast.Expr{e.Index}, e.Rbrack
case *ast.IndexListExpr:
return e.X, e.Lbrack, e.Indices, e.Rbrack
}
return nil, token.NoPos, nil, token.NoPos
}
// PackIndexExpr returns an *ast.IndexExpr or *ast.IndexListExpr, depending on
// the cardinality of indices. Calling PackIndexExpr with len(indices) == 0
// will panic.
func PackIndexExpr(x ast.Expr, lbrack token.Pos, indices []ast.Expr, rbrack token.Pos) ast.Expr {
switch len(indices) {
case 0:
panic("empty indices")
case 1:
return &ast.IndexExpr{
X: x,
Lbrack: lbrack,
Index: indices[0],
Rbrack: rbrack,
}
default:
return &ast.IndexListExpr{
X: x,
Lbrack: lbrack,
Indices: indices,
Rbrack: rbrack,
}
}
}
// IsTypeParam reports whether t is a type parameter (or an alias of one).
func IsTypeParam(t types.Type) bool {
_, ok := types.Unalias(t).(*types.TypeParam)
return ok
}
-157
View File
@@ -1,157 +0,0 @@
// Copyright 2022 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 typeparams
import (
"fmt"
"go/types"
)
// CoreType returns the core type of T or nil if T does not have a core type.
//
// As of Go1.25, the notion of a core type has been removed from the language spec.
// See https://go.dev/blog/coretypes for more details.
// TODO(mkalil): We should eventually consider removing all uses of CoreType.
func CoreType(T types.Type) types.Type {
U := T.Underlying()
if _, ok := U.(*types.Interface); !ok {
return U // for non-interface types,
}
terms, err := NormalTerms(U)
if len(terms) == 0 || err != nil {
// len(terms) -> empty type set of interface.
// err != nil => U is invalid, exceeds complexity bounds, or has an empty type set.
return nil // no core type.
}
U = terms[0].Type().Underlying()
var identical int // i in [0,identical) => Identical(U, terms[i].Type().Underlying())
for identical = 1; identical < len(terms); identical++ {
if !types.Identical(U, terms[identical].Type().Underlying()) {
break
}
}
if identical == len(terms) {
// From the deprecated core types spec:
// "There is a single type U which is the underlying type of all types in the type set of T"
return U
}
ch, ok := U.(*types.Chan)
if !ok {
return nil // no core type as identical < len(terms) and U is not a channel.
}
// From the deprecated core types spec:
// "the type chan E if T contains only bidirectional channels, or the type chan<- E or
// <-chan E depending on the direction of the directional channels present."
for chans := identical; chans < len(terms); chans++ {
curr, ok := terms[chans].Type().Underlying().(*types.Chan)
if !ok {
return nil
}
if !types.Identical(ch.Elem(), curr.Elem()) {
return nil // channel elements are not identical.
}
if ch.Dir() == types.SendRecv {
// ch is bidirectional. We can safely always use curr's direction.
ch = curr
} else if curr.Dir() != types.SendRecv && ch.Dir() != curr.Dir() {
// ch and curr are not bidirectional and not the same direction.
return nil
}
}
return ch
}
// NormalTerms returns a slice of terms representing the normalized structural
// type restrictions of a type, if any.
//
// For all types other than *types.TypeParam, *types.Interface, and
// *types.Union, this is just a single term with Tilde() == false and
// Type() == typ. For *types.TypeParam, *types.Interface, and *types.Union, see
// below.
//
// Structural type restrictions of a type parameter are created via
// non-interface types embedded in its constraint interface (directly, or via a
// chain of interface embeddings). For example, in the declaration type
// T[P interface{~int; m()}] int the structural restriction of the type
// parameter P is ~int.
//
// With interface embedding and unions, the specification of structural type
// restrictions may be arbitrarily complex. For example, consider the
// following:
//
// type A interface{ ~string|~[]byte }
//
// type B interface{ int|string }
//
// type C interface { ~string|~int }
//
// type T[P interface{ A|B; C }] int
//
// In this example, the structural type restriction of P is ~string|int: A|B
// expands to ~string|~[]byte|int|string, which reduces to ~string|~[]byte|int,
// which when intersected with C (~string|~int) yields ~string|int.
//
// NormalTerms computes these expansions and reductions, producing a
// "normalized" form of the embeddings. A structural restriction is normalized
// if it is a single union containing no interface terms, and is minimal in the
// sense that removing any term changes the set of types satisfying the
// constraint. It is left as a proof for the reader that, modulo sorting, there
// is exactly one such normalized form.
//
// Because the minimal representation always takes this form, NormalTerms
// returns a slice of tilde terms corresponding to the terms of the union in
// the normalized structural restriction. An error is returned if the type is
// invalid, exceeds complexity bounds, or has an empty type set. In the latter
// case, NormalTerms returns ErrEmptyTypeSet.
//
// NormalTerms makes no guarantees about the order of terms, except that it
// is deterministic.
func NormalTerms(T types.Type) ([]*types.Term, error) {
// typeSetOf(T) == typeSetOf(Unalias(T))
typ := types.Unalias(T)
if named, ok := typ.(*types.Named); ok {
typ = named.Underlying()
}
switch typ := typ.(type) {
case *types.TypeParam:
return StructuralTerms(typ)
case *types.Union:
return UnionTermSet(typ)
case *types.Interface:
return InterfaceTermSet(typ)
default:
return []*types.Term{types.NewTerm(false, T)}, nil
}
}
// Deref returns the type of the variable pointed to by t,
// if t's core type is a pointer; otherwise it returns t.
//
// Do not assume that Deref(T)==T implies T is not a pointer:
// consider "type T *T", for example.
//
// TODO(adonovan): ideally this would live in typesinternal, but that
// creates an import cycle. Move there when we melt this package down.
func Deref(t types.Type) types.Type {
if ptr, ok := CoreType(t).(*types.Pointer); ok {
return ptr.Elem()
}
return t
}
// MustDeref returns the type of the variable pointed to by t.
// It panics if t's core type is not a pointer.
//
// TODO(adonovan): ideally this would live in typesinternal, but that
// creates an import cycle. Move there when we melt this package down.
func MustDeref(t types.Type) types.Type {
if ptr, ok := CoreType(t).(*types.Pointer); ok {
return ptr.Elem()
}
panic(fmt.Sprintf("%v is not a pointer", t))
}
-129
View File
@@ -1,129 +0,0 @@
// Copyright 2024 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 typeparams
import (
"go/types"
)
// Free is a memoization of the set of free type parameters within a
// type. It makes a sequence of calls to [Free.Has] for overlapping
// types more efficient. The zero value is ready for use.
//
// NOTE: Adapted from go/types/infer.go. If it is later exported, factor.
type Free struct {
seen map[types.Type]bool
}
// Has reports whether the specified type has a free type parameter.
func (w *Free) Has(typ types.Type) (res bool) {
// detect cycles
if x, ok := w.seen[typ]; ok {
return x
}
if w.seen == nil {
w.seen = make(map[types.Type]bool)
}
w.seen[typ] = false
defer func() {
w.seen[typ] = res
}()
switch t := typ.(type) {
case nil, *types.Basic: // TODO(gri) should nil be handled here?
break
case *types.Alias:
if t.TypeParams().Len() > t.TypeArgs().Len() {
return true // This is an uninstantiated Alias.
}
// The expansion of an alias can have free type parameters,
// whether or not the alias itself has type parameters:
//
// func _[K comparable]() {
// type Set = map[K]bool // free(Set) = {K}
// type MapTo[V] = map[K]V // free(Map[foo]) = {V}
// }
//
// So, we must Unalias.
return w.Has(types.Unalias(t))
case *types.Array:
return w.Has(t.Elem())
case *types.Slice:
return w.Has(t.Elem())
case *types.Struct:
for i, n := 0, t.NumFields(); i < n; i++ {
if w.Has(t.Field(i).Type()) {
return true
}
}
case *types.Pointer:
return w.Has(t.Elem())
case *types.Tuple:
n := t.Len()
for i := range n {
if w.Has(t.At(i).Type()) {
return true
}
}
case *types.Signature:
// t.tparams may not be nil if we are looking at a signature
// of a generic function type (or an interface method) that is
// part of the type we're testing. We don't care about these type
// parameters.
// Similarly, the receiver of a method may declare (rather than
// use) type parameters, we don't care about those either.
// Thus, we only need to look at the input and result parameters.
return w.Has(t.Params()) || w.Has(t.Results())
case *types.Interface:
for i, n := 0, t.NumMethods(); i < n; i++ {
if w.Has(t.Method(i).Type()) {
return true
}
}
terms, err := InterfaceTermSet(t)
if err != nil {
return false // ill typed
}
for _, term := range terms {
if w.Has(term.Type()) {
return true
}
}
case *types.Map:
return w.Has(t.Key()) || w.Has(t.Elem())
case *types.Chan:
return w.Has(t.Elem())
case *types.Named:
args := t.TypeArgs()
if params := t.TypeParams(); params.Len() > args.Len() {
return true // this is an uninstantiated named type.
}
for i, n := 0, args.Len(); i < n; i++ {
if w.Has(args.At(i)) {
return true
}
}
return w.Has(t.Underlying()) // recurse for types local to parameterized functions
case *types.TypeParam:
return true
default:
panic(t) // unreachable
}
return false
}
-216
View File
@@ -1,216 +0,0 @@
// Copyright 2021 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 typeparams
import (
"errors"
"fmt"
"go/types"
"os"
"strings"
)
//go:generate go run copytermlist.go
const debug = false
var ErrEmptyTypeSet = errors.New("empty type set")
// StructuralTerms returns a slice of terms representing the normalized
// structural type restrictions of a type parameter, if any.
//
// Structural type restrictions of a type parameter are created via
// non-interface types embedded in its constraint interface (directly, or via a
// chain of interface embeddings). For example, in the declaration
//
// type T[P interface{~int; m()}] int
//
// the structural restriction of the type parameter P is ~int.
//
// With interface embedding and unions, the specification of structural type
// restrictions may be arbitrarily complex. For example, consider the
// following:
//
// type A interface{ ~string|~[]byte }
//
// type B interface{ int|string }
//
// type C interface { ~string|~int }
//
// type T[P interface{ A|B; C }] int
//
// In this example, the structural type restriction of P is ~string|int: A|B
// expands to ~string|~[]byte|int|string, which reduces to ~string|~[]byte|int,
// which when intersected with C (~string|~int) yields ~string|int.
//
// StructuralTerms computes these expansions and reductions, producing a
// "normalized" form of the embeddings. A structural restriction is normalized
// if it is a single union containing no interface terms, and is minimal in the
// sense that removing any term changes the set of types satisfying the
// constraint. It is left as a proof for the reader that, modulo sorting, there
// is exactly one such normalized form.
//
// Because the minimal representation always takes this form, StructuralTerms
// returns a slice of tilde terms corresponding to the terms of the union in
// the normalized structural restriction. An error is returned if the
// constraint interface is invalid, exceeds complexity bounds, or has an empty
// type set. In the latter case, StructuralTerms returns ErrEmptyTypeSet.
//
// StructuralTerms makes no guarantees about the order of terms, except that it
// is deterministic.
func StructuralTerms(tparam *types.TypeParam) ([]*types.Term, error) {
constraint := tparam.Constraint()
if constraint == nil {
return nil, fmt.Errorf("%s has nil constraint", tparam)
}
iface, _ := constraint.Underlying().(*types.Interface)
if iface == nil {
return nil, fmt.Errorf("constraint is %T, not *types.Interface", constraint.Underlying())
}
return InterfaceTermSet(iface)
}
// InterfaceTermSet computes the normalized terms for a constraint interface,
// returning an error if the term set cannot be computed or is empty. In the
// latter case, the error will be ErrEmptyTypeSet.
//
// See the documentation of StructuralTerms for more information on
// normalization.
func InterfaceTermSet(iface *types.Interface) ([]*types.Term, error) {
return computeTermSet(iface)
}
// UnionTermSet computes the normalized terms for a union, returning an error
// if the term set cannot be computed or is empty. In the latter case, the
// error will be ErrEmptyTypeSet.
//
// See the documentation of StructuralTerms for more information on
// normalization.
func UnionTermSet(union *types.Union) ([]*types.Term, error) {
return computeTermSet(union)
}
func computeTermSet(typ types.Type) ([]*types.Term, error) {
tset, err := computeTermSetInternal(typ, make(map[types.Type]*termSet), 0)
if err != nil {
return nil, err
}
if tset.terms.isEmpty() {
return nil, ErrEmptyTypeSet
}
if tset.terms.isAll() {
return nil, nil
}
var terms []*types.Term
for _, term := range tset.terms {
terms = append(terms, types.NewTerm(term.tilde, term.typ))
}
return terms, nil
}
// A termSet holds the normalized set of terms for a given type.
//
// The name termSet is intentionally distinct from 'type set': a type set is
// all types that implement a type (and includes method restrictions), whereas
// a term set just represents the structural restrictions on a type.
type termSet struct {
complete bool
terms termlist
}
func indentf(depth int, format string, args ...any) {
fmt.Fprintf(os.Stderr, strings.Repeat(".", depth)+format+"\n", args...)
}
func computeTermSetInternal(t types.Type, seen map[types.Type]*termSet, depth int) (res *termSet, err error) {
if t == nil {
panic("nil type")
}
if debug {
indentf(depth, "%s", t.String())
defer func() {
if err != nil {
indentf(depth, "=> %s", err)
} else {
indentf(depth, "=> %s", res.terms.String())
}
}()
}
const maxTermCount = 100
if tset, ok := seen[t]; ok {
if !tset.complete {
return nil, fmt.Errorf("cycle detected in the declaration of %s", t)
}
return tset, nil
}
// Mark the current type as seen to avoid infinite recursion.
tset := new(termSet)
defer func() {
tset.complete = true
}()
seen[t] = tset
switch u := t.Underlying().(type) {
case *types.Interface:
// The term set of an interface is the intersection of the term sets of its
// embedded types.
tset.terms = allTermlist
for embedded := range u.EmbeddedTypes() {
if _, ok := embedded.Underlying().(*types.TypeParam); ok {
return nil, fmt.Errorf("invalid embedded type %T", embedded)
}
tset2, err := computeTermSetInternal(embedded, seen, depth+1)
if err != nil {
return nil, err
}
tset.terms = tset.terms.intersect(tset2.terms)
}
case *types.Union:
// The term set of a union is the union of term sets of its terms.
tset.terms = nil
for t := range u.Terms() {
var terms termlist
switch t.Type().Underlying().(type) {
case *types.Interface:
tset2, err := computeTermSetInternal(t.Type(), seen, depth+1)
if err != nil {
return nil, err
}
terms = tset2.terms
case *types.TypeParam, *types.Union:
// A stand-alone type parameter or union is not permitted as union
// term.
return nil, fmt.Errorf("invalid union term %T", t)
default:
if t.Type() == types.Typ[types.Invalid] {
continue
}
terms = termlist{{t.Tilde(), t.Type()}}
}
tset.terms = tset.terms.union(terms)
if len(tset.terms) > maxTermCount {
return nil, fmt.Errorf("exceeded max term count %d", maxTermCount)
}
}
case *types.TypeParam:
panic("unreachable")
default:
// For all other types, the term set is just a single non-tilde term
// holding the type itself.
if u != types.Typ[types.Invalid] {
tset.terms = termlist{{false, t}}
}
}
return tset, nil
}
// under is a facade for the go/types internal function of the same name. It is
// used by typeterm.go.
func under(t types.Type) types.Type {
return t.Underlying()
}
-169
View File
@@ -1,169 +0,0 @@
// Code generated by "go test -run=Generate -write=all"; DO NOT EDIT.
// Source: ../../cmd/compile/internal/types2/termlist.go
// Copyright 2021 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.
// Code generated by copytermlist.go DO NOT EDIT.
package typeparams
import (
"go/types"
"strings"
)
// A termlist represents the type set represented by the union
// t1 ∪ y2 ∪ ... tn of the type sets of the terms t1 to tn.
// A termlist is in normal form if all terms are disjoint.
// termlist operations don't require the operands to be in
// normal form.
type termlist []*term
// allTermlist represents the set of all types.
// It is in normal form.
var allTermlist = termlist{new(term)}
// termSep is the separator used between individual terms.
const termSep = " | "
// String prints the termlist exactly (without normalization).
func (xl termlist) String() string {
if len(xl) == 0 {
return "∅"
}
var buf strings.Builder
for i, x := range xl {
if i > 0 {
buf.WriteString(termSep)
}
buf.WriteString(x.String())
}
return buf.String()
}
// isEmpty reports whether the termlist xl represents the empty set of types.
func (xl termlist) isEmpty() bool {
// If there's a non-nil term, the entire list is not empty.
// If the termlist is in normal form, this requires at most
// one iteration.
for _, x := range xl {
if x != nil {
return false
}
}
return true
}
// isAll reports whether the termlist xl represents the set of all types.
func (xl termlist) isAll() bool {
// If there's a 𝓤 term, the entire list is 𝓤.
// If the termlist is in normal form, this requires at most
// one iteration.
for _, x := range xl {
if x != nil && x.typ == nil {
return true
}
}
return false
}
// norm returns the normal form of xl.
func (xl termlist) norm() termlist {
// Quadratic algorithm, but good enough for now.
// TODO(gri) fix asymptotic performance
used := make([]bool, len(xl))
var rl termlist
for i, xi := range xl {
if xi == nil || used[i] {
continue
}
for j := i + 1; j < len(xl); j++ {
xj := xl[j]
if xj == nil || used[j] {
continue
}
if u1, u2 := xi.union(xj); u2 == nil {
// If we encounter a 𝓤 term, the entire list is 𝓤.
// Exit early.
// (Note that this is not just an optimization;
// if we continue, we may end up with a 𝓤 term
// and other terms and the result would not be
// in normal form.)
if u1.typ == nil {
return allTermlist
}
xi = u1
used[j] = true // xj is now unioned into xi - ignore it in future iterations
}
}
rl = append(rl, xi)
}
return rl
}
// union returns the union xl ∪ yl.
func (xl termlist) union(yl termlist) termlist {
return append(xl, yl...).norm()
}
// intersect returns the intersection xl ∩ yl.
func (xl termlist) intersect(yl termlist) termlist {
if xl.isEmpty() || yl.isEmpty() {
return nil
}
// Quadratic algorithm, but good enough for now.
// TODO(gri) fix asymptotic performance
var rl termlist
for _, x := range xl {
for _, y := range yl {
if r := x.intersect(y); r != nil {
rl = append(rl, r)
}
}
}
return rl.norm()
}
// equal reports whether xl and yl represent the same type set.
func (xl termlist) equal(yl termlist) bool {
// TODO(gri) this should be more efficient
return xl.subsetOf(yl) && yl.subsetOf(xl)
}
// includes reports whether t ∈ xl.
func (xl termlist) includes(t types.Type) bool {
for _, x := range xl {
if x.includes(t) {
return true
}
}
return false
}
// supersetOf reports whether y ⊆ xl.
func (xl termlist) supersetOf(y *term) bool {
for _, x := range xl {
if y.subsetOf(x) {
return true
}
}
return false
}
// subsetOf reports whether xl ⊆ yl.
func (xl termlist) subsetOf(yl termlist) bool {
if yl.isEmpty() {
return xl.isEmpty()
}
// each term x of xl must be a subset of yl
for _, x := range xl {
if !yl.supersetOf(x) {
return false // x is not a subset yl
}
}
return true
}
-172
View File
@@ -1,172 +0,0 @@
// Code generated by "go test -run=Generate -write=all"; DO NOT EDIT.
// Source: ../../cmd/compile/internal/types2/typeterm.go
// Copyright 2021 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.
// Code generated by copytermlist.go DO NOT EDIT.
package typeparams
import "go/types"
// A term describes elementary type sets:
//
// ∅: (*term)(nil) == ∅ // set of no types (empty set)
// 𝓤: &term{} == 𝓤 // set of all types (𝓤niverse)
// T: &term{false, T} == {T} // set of type T
// ~t: &term{true, t} == {t' | under(t') == t} // set of types with underlying type t
type term struct {
tilde bool // valid if typ != nil
typ types.Type
}
func (x *term) String() string {
switch {
case x == nil:
return "∅"
case x.typ == nil:
return "𝓤"
case x.tilde:
return "~" + x.typ.String()
default:
return x.typ.String()
}
}
// equal reports whether x and y represent the same type set.
func (x *term) equal(y *term) bool {
// easy cases
switch {
case x == nil || y == nil:
return x == y
case x.typ == nil || y.typ == nil:
return x.typ == y.typ
}
// ∅ ⊂ x, y ⊂ 𝓤
return x.tilde == y.tilde && types.Identical(x.typ, y.typ)
}
// union returns the union x ∪ y: zero, one, or two non-nil terms.
func (x *term) union(y *term) (_, _ *term) {
// easy cases
switch {
case x == nil && y == nil:
return nil, nil // ∅ ∪ ∅ == ∅
case x == nil:
return y, nil // ∅ ∪ y == y
case y == nil:
return x, nil // x ∪ ∅ == x
case x.typ == nil:
return x, nil // 𝓤 ∪ y == 𝓤
case y.typ == nil:
return y, nil // x ∪ 𝓤 == 𝓤
}
// ∅ ⊂ x, y ⊂ 𝓤
if x.disjoint(y) {
return x, y // x ∪ y == (x, y) if x ∩ y == ∅
}
// x.typ == y.typ
// ~t ∪ ~t == ~t
// ~t ∪ T == ~t
// T ∪ ~t == ~t
// T ∪ T == T
if x.tilde || !y.tilde {
return x, nil
}
return y, nil
}
// intersect returns the intersection x ∩ y.
func (x *term) intersect(y *term) *term {
// easy cases
switch {
case x == nil || y == nil:
return nil // ∅ ∩ y == ∅ and ∩ ∅ == ∅
case x.typ == nil:
return y // 𝓤 ∩ y == y
case y.typ == nil:
return x // x ∩ 𝓤 == x
}
// ∅ ⊂ x, y ⊂ 𝓤
if x.disjoint(y) {
return nil // x ∩ y == ∅ if x ∩ y == ∅
}
// x.typ == y.typ
// ~t ∩ ~t == ~t
// ~t ∩ T == T
// T ∩ ~t == T
// T ∩ T == T
if !x.tilde || y.tilde {
return x
}
return y
}
// includes reports whether t ∈ x.
func (x *term) includes(t types.Type) bool {
// easy cases
switch {
case x == nil:
return false // t ∈ ∅ == false
case x.typ == nil:
return true // t ∈ 𝓤 == true
}
// ∅ ⊂ x ⊂ 𝓤
u := t
if x.tilde {
u = under(u)
}
return types.Identical(x.typ, u)
}
// subsetOf reports whether x ⊆ y.
func (x *term) subsetOf(y *term) bool {
// easy cases
switch {
case x == nil:
return true // ∅ ⊆ y == true
case y == nil:
return false // x ⊆ ∅ == false since x != ∅
case y.typ == nil:
return true // x ⊆ 𝓤 == true
case x.typ == nil:
return false // 𝓤 ⊆ y == false since y != 𝓤
}
// ∅ ⊂ x, y ⊂ 𝓤
if x.disjoint(y) {
return false // x ⊆ y == false if x ∩ y == ∅
}
// x.typ == y.typ
// ~t ⊆ ~t == true
// ~t ⊆ T == false
// T ⊆ ~t == true
// T ⊆ T == true
return !x.tilde || y.tilde
}
// disjoint reports whether x ∩ y == ∅.
// x.typ and y.typ must not be nil.
func (x *term) disjoint(y *term) bool {
if debug && (x.typ == nil || y.typ == nil) {
panic("invalid argument(s)")
}
ux := x.typ
if y.tilde {
ux = under(ux)
}
uy := y.typ
if x.tilde {
uy = under(uy)
}
return !types.Identical(ux, uy)
}
+128
View File
@@ -0,0 +1,128 @@
// Copyright 2026 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 typesinternal
import (
"go/ast"
"go/token"
"go/types"
"golang.org/x/tools/go/ast/edge"
"golang.org/x/tools/go/ast/inspector"
)
// IsAssignedOrAddressTaken reports whether the expression cur denotes a
// variable and appears in a context that assigns it or that takes its address,
// potentially leading to indirect assignment.
//
// These examples cause IsAssignedOrAddressTaken on the identifier for x to
// return true:
//
// x = 1
// x++
// x[i] = 1 (assume x is an array)
// x.a[i] = 1 (assume x.a is a non-pointer struct field)
// use(&x)
//
// whereas these cause it to return false:
//
// y = x
// f(x)
// use(x.a[i])
// use(*x)
//
// The expression may itself be a compound, for example:
//
// use(&(*ptr)) => IsAssignedOrAddressTaken("*ptr") = true
// x.a[i] = 1 => IsAssignedOrAddressTaken("x.a") = true
// _ = x.a[i] => IsAssignedOrAddressTaken("x.a") = false
//
// A variable's declaration is not considered to be an assignment:
//
// var x int => IsAssignedOrAddressTaken(x) = false
// x := 1 => IsAssignedOrAddressTaken(x) = false
//
// TODO(adonovan): revisit the surprising behavior for declarations.
func IsAssignedOrAddressTaken(info *types.Info, cur inspector.Cursor) bool {
// Unfortunately we can't simply use info.Types[e].Assignable()
// as it is always true for a variable even when that variable is
// used only as an r-value. So we must inspect enclosing syntax.
outer:
// Ascend to outermost aggregate of which
// original cur is a part:
// x -> (x) | x.f | x[i] | x[i:j]
for cur = range cur.Enclosing() {
switch cur.ParentEdgeKind() {
case edge.ParenExpr_X:
// If x is an lvalue, then (x) is an lvalue.
case edge.SelectorExpr_X:
// If x is an lvalue, then x.f is an lvalue iff
// the selection does not traverse a pointer.
sel := cur.Parent().Node().(*ast.SelectorExpr)
if seln, ok := info.Selections[sel]; ok {
// Note: there is a bug in Indirect() where it spuriously returns true
// when both the selection receiver and parameter are pointers. However,
// it's okay in this case because there is no address taken when a
// pointer receiver method is called on a pointer type.
if seln.Indirect() {
return false
}
if seln.Kind() == types.MethodVal {
sig := seln.Obj().Type().(*types.Signature)
if is[*types.Pointer](sig.Recv().Type().Underlying()) {
t := seln.Recv()
// The receiver may be an embedded field, so we need
// to get the inner-most type (right before the method
// call in seln.Index())
for _, idx := range seln.Index()[:len(seln.Index())-1] {
t = t.Underlying().(*types.Struct).Field(idx).Type()
}
if !is[*types.Pointer](t.Underlying()) {
return true // takes address of receiver
}
}
return false
}
}
case edge.IndexExpr_X, edge.SliceExpr_X:
// If x[i] or x[i:j] is an lvalue,
// then x is an lvalue iff x is an array.
if !is[*types.Array](info.TypeOf(cur.Node().(ast.Expr)).Underlying()) {
return false
}
default:
break outer
}
}
switch cur.ParentEdgeKind() {
case edge.AssignStmt_Lhs:
assign := cur.Parent().Node().(*ast.AssignStmt)
if assign.Tok != token.DEFINE {
return true // x = j or x += j
}
id := cur.Node().(*ast.Ident)
// Re-assigned identifiers are recorded in the Uses map.
if _, ok := info.Uses[id]; ok {
return true // reassignment of x (x, y := 1, 2)
}
case edge.RangeStmt_Key, edge.RangeStmt_Value:
rng := cur.Parent().Node().(*ast.RangeStmt)
if rng.Tok == token.ASSIGN {
return true // "for k, v = range x" is like an AssignStmt to k, v
}
case edge.IncDecStmt_X:
return true // x++, x--
case edge.UnaryExpr_X:
if cur.Parent().Node().(*ast.UnaryExpr).Op == token.AND {
return true // &x
}
}
return false
}
func is[T any](x any) bool {
_, ok := x.(T)
return ok
}
+69 -8
View File
@@ -8,7 +8,6 @@ import (
"fmt"
"go/ast"
"go/types"
_ "unsafe" // for go:linkname hack
)
// CallKind describes the function position of an [*ast.CallExpr].
@@ -72,11 +71,15 @@ func ClassifyCall(info *types.Info, call *ast.CallExpr) CallKind {
if tv.IsBuiltin() {
return CallBuiltin
}
obj := info.Uses[UsedIdent(info, call.Fun)]
id := UsedIdent(info, call.Fun)
if id == nil {
return CallDynamic
}
obj := info.Uses[id]
// Classify the call by the type of the object, if any.
switch obj := obj.(type) {
case *types.Func:
if interfaceMethod(obj) {
if isInterfaceMethod(obj) {
return CallInterface
}
return CallStatic
@@ -127,11 +130,69 @@ func ClassifyCall(info *types.Info, call *ast.CallExpr) CallKind {
// Note: if e is an instantiated function or method, UsedIdent returns
// the corresponding generic function or method on the generic type.
func UsedIdent(info *types.Info, e ast.Expr) *ast.Ident {
return usedIdent(info, e)
if info.Types == nil || info.Uses == nil {
panic("one of info.Types or info.Uses is nil; both must be populated")
}
// Look through type instantiation if necessary.
switch d := ast.Unparen(e).(type) {
case *ast.IndexExpr:
if info.Types[d.Index].IsType() {
e = d.X
}
case *ast.IndexListExpr:
e = d.X
}
switch e := ast.Unparen(e).(type) {
// info.Uses always has the object we want, even for selector expressions.
// We don't need info.Selections.
// See go/types/recording.go:recordSelection.
case *ast.Ident:
return e
case *ast.SelectorExpr:
return e.Sel
}
return nil
}
//go:linkname usedIdent golang.org/x/tools/go/types/typeutil.usedIdent
func usedIdent(info *types.Info, e ast.Expr) *ast.Ident
// See [golang.org/x/tools/go/types/typeutil.Callee].
func Callee(info *types.Info, call *ast.CallExpr) types.Object {
id := UsedIdent(info, call.Fun)
if id == nil {
return nil
}
obj := info.Uses[id]
if obj == nil {
return nil
}
if _, ok := obj.(*types.TypeName); ok {
return nil
}
if fn, ok := obj.(*types.Func); ok {
return fn.Origin()
}
return obj
}
//go:linkname interfaceMethod golang.org/x/tools/go/types/typeutil.interfaceMethod
func interfaceMethod(f *types.Func) bool
// See [golang.org/x/tools/go/types/typeutil.StaticCallee].
func StaticCallee(info *types.Info, call *ast.CallExpr) *types.Func {
id := UsedIdent(info, call.Fun)
if id == nil {
return nil
}
obj := info.Uses[id]
if obj == nil {
return nil
}
fn, _ := obj.(*types.Func)
if fn == nil || isInterfaceMethod(fn) {
return nil
}
return fn.Origin()
}
// isInterfaceMethod reports whether its argument is a method of an interface.
func isInterfaceMethod(f *types.Func) bool {
recv := f.Signature().Recv()
return recv != nil && types.IsInterface(recv.Type())
}
+31 -34
View File
@@ -7,8 +7,6 @@ package typesinternal
import (
"fmt"
"go/types"
"golang.org/x/tools/go/types/typeutil"
)
// ForEachElement calls f for type T and each type reachable from its
@@ -16,25 +14,24 @@ import (
// type constructors; in addition, for each named type N, the type *N
// is added to the result as it may have additional methods.
//
// The caller must provide an initially empty set used to de-duplicate
// identical types, potentially across multiple calls to ForEachElement.
// (Its final value holds all the elements seen, matching the arguments
// passed to f.)
// The access argument passed to f indicates whether the type is
// inaccessible to reflection (for example, intermediate tuple types
// or underlying types of named types).
//
// TODO(adonovan): share/harmonize with go/callgraph/rta.
func ForEachElement(rtypes *typeutil.Map, msets *typeutil.MethodSetCache, T types.Type, f func(types.Type)) {
var visit func(T types.Type, skip bool)
visit = func(T types.Type, skip bool) {
if !skip {
if seen, _ := rtypes.Set(T, true).(bool); seen {
return // de-dup
}
f(T) // notify caller of new element type
// The result of f indicates whether the caller has seen this type
// already, so we can prune the traversal.
//
// methodSetOf abstracts (*typeutil.MethodSetCache).MethodSet,
// avoiding an import cycle.
func ForEachElement(methodSetOf func(types.Type) *types.MethodSet, T types.Type, f func(T types.Type, access bool) bool) {
var visit func(T types.Type, access bool)
visit = func(T types.Type, access bool) {
if f(T, access) {
return // duplicate; prune descent
}
// Recursion over signatures of each method.
tmset := msets.MethodSet(T)
tmset := methodSetOf(T)
for method := range tmset.Methods() {
sig := method.Type().(*types.Signature)
if sig.TypeParams() != nil {
@@ -65,13 +62,13 @@ func ForEachElement(rtypes *typeutil.Map, msets *typeutil.MethodSetCache, T type
//
// TODO(adonovan): document whether or not it is
// safe to skip non-exported methods (as RTA does).
visit(sig.Params(), true) // skip the Tuple
visit(sig.Results(), true) // skip the Tuple
visit(sig.Params(), false) // the Tuple is inaccessible
visit(sig.Results(), false) // the Tuple is inaccessible
}
switch T := T.(type) {
case *types.Alias:
visit(types.Unalias(T), skip) // emulates the pre-Alias behavior
visit(types.Unalias(T), access) // emulates the pre-Alias behavior
case *types.Basic:
// nop
@@ -80,49 +77,49 @@ func ForEachElement(rtypes *typeutil.Map, msets *typeutil.MethodSetCache, T type
// nop---handled by recursion over method set.
case *types.Pointer:
visit(T.Elem(), false)
visit(T.Elem(), true)
case *types.Slice:
visit(T.Elem(), false)
visit(T.Elem(), true)
case *types.Chan:
visit(T.Elem(), false)
visit(T.Elem(), true)
case *types.Map:
visit(T.Key(), false)
visit(T.Elem(), false)
visit(T.Key(), true)
visit(T.Elem(), true)
case *types.Signature:
if T.Recv() != nil {
panic(fmt.Sprintf("Signature %s has Recv %s", T, T.Recv()))
}
visit(T.Params(), true) // skip the Tuple
visit(T.Results(), true) // skip the Tuple
visit(T.Params(), false) // the Tuple is inaccessible
visit(T.Results(), false) // the Tuple is inaccessible
case *types.Named:
// A pointer-to-named type can be derived from a named
// type via reflection. It may have methods too.
visit(types.NewPointer(T), false)
visit(types.NewPointer(T), true)
// Consider 'type T struct{S}' where S has methods.
// Reflection provides no way to get from T to struct{S},
// only to S, so the method set of struct{S} is unwanted,
// so set 'skip' flag during recursion.
visit(T.Underlying(), true) // skip the unnamed type
// so mark it inaccessible during recursion.
visit(T.Underlying(), false) // skip the unnamed type
case *types.Array:
visit(T.Elem(), false)
visit(T.Elem(), true)
case *types.Struct:
for i, n := 0, T.NumFields(); i < n; i++ {
// TODO(adonovan): document whether or not
// it is safe to skip non-exported fields.
visit(T.Field(i).Type(), false)
visit(T.Field(i).Type(), true)
}
case *types.Tuple:
for i, n := 0, T.Len(); i < n; i++ {
visit(T.At(i).Type(), false)
visit(T.At(i).Type(), true)
}
case *types.TypeParam, *types.Union:
@@ -133,5 +130,5 @@ func ForEachElement(rtypes *typeutil.Map, msets *typeutil.MethodSetCache, T type
panic(fmt.Sprintf("ForEachElement called on unexpected type %T", T))
}
}
visit(T, false)
visit(T, true)
}
+31 -13
View File
@@ -13,20 +13,30 @@ import (
// TooNewStdSymbols computes the set of package-level symbols
// exported by pkg that are not available at the specified version.
// The result maps each symbol to its minimum version.
//
// The pkg is allowed to contain type errors.
func TooNewStdSymbols(pkg *types.Package, version string) map[types.Object]string {
disallowed := make(map[types.Object]string)
func TooNewStdSymbols(pkg *types.Package, version string) map[types.Object]stdlib.Symbol {
disallowed := make(map[types.Object]stdlib.Symbol)
// Some symbols are accessible before their release but
// only with specific build tags unknown to us here.
// Avoid false positives in such cases.
if pkg.Path() == "testing/synctest" && versions.AtLeast(version, "go1.24") {
// requires go1.24 && goexperiment.synctest || go1.25
return disallowed
}
if (pkg.Path() == "encoding/json/v2" || pkg.Path() == "encoding/json/jsontext") && versions.AtLeast(version, "go1.25") {
// requires go1.25 && goexperiment.jsonv2 || go1.27
return disallowed
}
// Pass 1: package-level symbols.
symbols := stdlib.PackageSymbols[pkg.Path()]
for _, sym := range symbols {
symver := sym.Version.String()
if versions.Before(version, symver) {
if versions.Before(version, sym.Version.String()) {
switch sym.Kind {
case stdlib.Func, stdlib.Var, stdlib.Const, stdlib.Type:
disallowed[pkg.Scope().Lookup(sym.Name)] = symver
disallowed[pkg.Scope().Lookup(sym.Name)] = sym
}
}
}
@@ -60,28 +70,36 @@ func TooNewStdSymbols(pkg *types.Package, version string) map[types.Object]strin
// spuriously cause the analyzer to report a reference to a
// too-new symbol even though this expression compiles just
// fine (with the fake implementation) using go1.21.
var noSym stdlib.Symbol
depth := make(map[types.Object]int)
for _, sym := range symbols {
symVersion := sym.Version.String()
if !versions.Before(version, symVersion) {
if !versions.Before(version, sym.Version.String()) {
continue // allowed
}
var obj types.Object
var indices []int
switch sym.Kind {
case stdlib.Field:
typename, name := sym.SplitField()
if t := pkg.Scope().Lookup(typename); t != nil && disallowed[t] == "" {
obj, _, _ = types.LookupFieldOrMethod(t.Type(), false, pkg, name)
if t := pkg.Scope().Lookup(typename); t != nil && disallowed[t] == noSym {
obj, indices, _ = types.LookupFieldOrMethod(t.Type(), false, pkg, name)
}
case stdlib.Method:
ptr, recvname, name := sym.SplitMethod()
if t := pkg.Scope().Lookup(recvname); t != nil && disallowed[t] == "" {
obj, _, _ = types.LookupFieldOrMethod(t.Type(), ptr, pkg, name)
if t := pkg.Scope().Lookup(recvname); t != nil && disallowed[t] == noSym {
obj, indices, _ = types.LookupFieldOrMethod(t.Type(), ptr, pkg, name)
}
}
if obj != nil {
disallowed[obj] = symVersion
// In the presence of embedding, two or more "pkg.T.name"
// strings may map to the same types.Object.
// Prefer the Object with the shorter index path.
if min, ok := depth[obj]; !ok || len(indices) < min {
depth[obj] = len(indices)
disallowed[obj] = sym
}
}
}
+8
View File
@@ -270,3 +270,11 @@ func ImplicitFieldSelections(seln types.Selection) iter.Seq2[*types.Var, bool] {
}
}
}
func TupleOf(elems ...types.Type) *types.Tuple {
params := make([]*types.Var, len(elems))
for i, elem := range elems {
params[i] = types.NewParam(token.NoPos, nil, "", elem)
}
return types.NewTuple(params...)
}
+6 -6
View File
@@ -287,7 +287,7 @@ github.com/cenkalti/backoff
# github.com/cenkalti/backoff/v5 v5.0.3
## explicit; go 1.23
github.com/cenkalti/backoff/v5
# github.com/ceph/go-ceph v0.40.0
# github.com/ceph/go-ceph v0.41.0
## explicit; go 1.25.0
github.com/ceph/go-ceph/cephfs
github.com/ceph/go-ceph/cephfs/admin
@@ -1323,7 +1323,7 @@ github.com/orcaman/concurrent-map
# github.com/owncloud/libre-graph-api-go v1.0.5-0.20260216101009-eeac018af245
## explicit; go 1.18
github.com/owncloud/libre-graph-api-go
# github.com/owncloud/reva/v2 v2.0.0-20260813121157-d386075a0421
# github.com/owncloud/reva/v2 v2.0.0-20260821144357-79bb0520701d
## explicit; go 1.26
github.com/owncloud/reva/v2/cmd/revad/internal/grace
github.com/owncloud/reva/v2/cmd/revad/runtime
@@ -1686,6 +1686,7 @@ github.com/owncloud/reva/v2/pkg/token/manager/jwt
github.com/owncloud/reva/v2/pkg/token/manager/loader
github.com/owncloud/reva/v2/pkg/token/manager/registry
github.com/owncloud/reva/v2/pkg/trace
github.com/owncloud/reva/v2/pkg/upload
github.com/owncloud/reva/v2/pkg/user
github.com/owncloud/reva/v2/pkg/user/manager/demo
github.com/owncloud/reva/v2/pkg/user/manager/json
@@ -2300,7 +2301,7 @@ golang.org/x/image/vector
golang.org/x/image/vp8
golang.org/x/image/vp8l
golang.org/x/image/webp
# golang.org/x/mod v0.38.0
# golang.org/x/mod v0.40.0
## explicit; go 1.25.0
golang.org/x/mod/internal/lazyregexp
golang.org/x/mod/module
@@ -2381,7 +2382,7 @@ golang.org/x/text/width
# golang.org/x/time v0.15.0
## explicit; go 1.25.0
golang.org/x/time/rate
# golang.org/x/tools v0.48.0
# golang.org/x/tools v0.49.0
## explicit; go 1.25.0
golang.org/x/tools/cover
golang.org/x/tools/go/ast/astutil
@@ -2390,7 +2391,6 @@ golang.org/x/tools/go/ast/inspector
golang.org/x/tools/go/gcexportdata
golang.org/x/tools/go/packages
golang.org/x/tools/go/types/objectpath
golang.org/x/tools/go/types/typeutil
golang.org/x/tools/imports
golang.org/x/tools/internal/aliases
golang.org/x/tools/internal/event
@@ -2402,10 +2402,10 @@ golang.org/x/tools/internal/gocommand
golang.org/x/tools/internal/gopathwalk
golang.org/x/tools/internal/imports
golang.org/x/tools/internal/modindex
golang.org/x/tools/internal/moremaps
golang.org/x/tools/internal/packagesinternal
golang.org/x/tools/internal/pkgbits
golang.org/x/tools/internal/stdlib
golang.org/x/tools/internal/typeparams
golang.org/x/tools/internal/typesinternal
golang.org/x/tools/internal/versions
# google.golang.org/genproto v0.0.0-20260319201613-d00831a3d3e7