You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

object.go 9.7 kB

2 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. package db
  2. import (
  3. "fmt"
  4. "time"
  5. "github.com/jmoiron/sqlx"
  6. "github.com/samber/lo"
  7. cdssdk "gitlink.org.cn/cloudream/common/sdks/storage"
  8. stgmod "gitlink.org.cn/cloudream/storage/common/models"
  9. "gitlink.org.cn/cloudream/storage/common/pkgs/db/model"
  10. coormq "gitlink.org.cn/cloudream/storage/common/pkgs/mq/coordinator"
  11. )
  12. type ObjectDB struct {
  13. *DB
  14. }
  15. func (db *DB) Object() *ObjectDB {
  16. return &ObjectDB{DB: db}
  17. }
  18. func (db *ObjectDB) GetByID(ctx SQLContext, objectID cdssdk.ObjectID) (model.Object, error) {
  19. var ret model.TempObject
  20. err := sqlx.Get(ctx, &ret, "select * from Object where ObjectID = ?", objectID)
  21. return ret.ToObject(), err
  22. }
  23. func (db *ObjectDB) BatchGetPackageObjectIDs(ctx SQLContext, pkgID cdssdk.PackageID, pathes []string) ([]cdssdk.ObjectID, error) {
  24. if len(pathes) == 0 {
  25. return nil, nil
  26. }
  27. // TODO In语句
  28. stmt, args, err := sqlx.In("select ObjectID from Object force index(PackagePath) where PackageID=? and Path in (?)", pkgID, pathes)
  29. if err != nil {
  30. return nil, err
  31. }
  32. stmt = ctx.Rebind(stmt)
  33. objIDs := make([]cdssdk.ObjectID, 0, len(pathes))
  34. err = sqlx.Select(ctx, &objIDs, stmt, args...)
  35. if err != nil {
  36. return nil, err
  37. }
  38. return objIDs, nil
  39. }
  40. func (db *ObjectDB) Create(ctx SQLContext, obj cdssdk.Object) (cdssdk.ObjectID, error) {
  41. sql := "insert into Object(PackageID, Path, Size, FileHash, Redundancy, CreateTime, UpdateTime) values(?,?,?,?,?,?,?)"
  42. ret, err := ctx.Exec(sql, obj.PackageID, obj.Path, obj.Size, obj.FileHash, obj.Redundancy, obj.UpdateTime, obj.UpdateTime)
  43. if err != nil {
  44. return 0, fmt.Errorf("insert object failed, err: %w", err)
  45. }
  46. objectID, err := ret.LastInsertId()
  47. if err != nil {
  48. return 0, fmt.Errorf("get id of inserted object failed, err: %w", err)
  49. }
  50. return cdssdk.ObjectID(objectID), nil
  51. }
  52. // 可以用于批量创建或者更新记录
  53. // 用于创建时,需要额外检查PackageID+Path的唯一性
  54. // 用于更新时,需要额外检查现存的PackageID+Path对应的ObjectID是否与待更新的ObjectID相同。不会更新CreateTime。
  55. func (db *ObjectDB) BatchCreateOrUpdate(ctx SQLContext, objs []cdssdk.Object) error {
  56. if len(objs) == 0 {
  57. return nil
  58. }
  59. sql := "insert into Object(PackageID, Path, Size, FileHash, Redundancy, CreateTime ,UpdateTime)" +
  60. " values(:PackageID,:Path,:Size,:FileHash,:Redundancy, :CreateTime, :UpdateTime) as new" +
  61. " on duplicate key update Size = new.Size, FileHash = new.FileHash, Redundancy = new.Redundancy, UpdateTime = new.UpdateTime"
  62. return BatchNamedExec(ctx, sql, 7, objs, nil)
  63. }
  64. func (*ObjectDB) GetPackageObjects(ctx SQLContext, packageID cdssdk.PackageID) ([]model.Object, error) {
  65. var ret []model.TempObject
  66. err := sqlx.Select(ctx, &ret, "select * from Object where PackageID = ? order by ObjectID asc", packageID)
  67. return lo.Map(ret, func(o model.TempObject, idx int) model.Object { return o.ToObject() }), err
  68. }
  69. func (db *ObjectDB) GetPackageObjectDetails(ctx SQLContext, packageID cdssdk.PackageID) ([]stgmod.ObjectDetail, error) {
  70. var objs []model.TempObject
  71. err := sqlx.Select(ctx, &objs, "select * from Object where PackageID = ? order by ObjectID asc", packageID)
  72. if err != nil {
  73. return nil, fmt.Errorf("getting objects: %w", err)
  74. }
  75. rets := make([]stgmod.ObjectDetail, 0, len(objs))
  76. var allBlocks []stgmod.ObjectBlock
  77. err = sqlx.Select(ctx, &allBlocks, "select ObjectBlock.* from ObjectBlock, Object where PackageID = ? and ObjectBlock.ObjectID = Object.ObjectID order by ObjectBlock.ObjectID, `Index` asc", packageID)
  78. if err != nil {
  79. return nil, fmt.Errorf("getting all object blocks: %w", err)
  80. }
  81. var allPinnedObjs []cdssdk.PinnedObject
  82. err = sqlx.Select(ctx, &allPinnedObjs, "select PinnedObject.* from PinnedObject, Object where PackageID = ? and PinnedObject.ObjectID = Object.ObjectID order by PinnedObject.ObjectID", packageID)
  83. if err != nil {
  84. return nil, fmt.Errorf("getting all pinned objects: %w", err)
  85. }
  86. blksCur := 0
  87. pinnedsCur := 0
  88. for _, temp := range objs {
  89. detail := stgmod.ObjectDetail{
  90. Object: temp.ToObject(),
  91. }
  92. // 1. 查询Object和ObjectBlock时均按照ObjectID升序排序
  93. // 2. ObjectBlock结果集中的不同ObjectID数只会比Object结果集的少
  94. // 因此在两个结果集上同时从头开始遍历时,如果两边的ObjectID字段不同,那么一定是ObjectBlock这边的ObjectID > Object的ObjectID,
  95. // 此时让Object的遍历游标前进,直到两边的ObjectID再次相等
  96. for ; blksCur < len(allBlocks); blksCur++ {
  97. if allBlocks[blksCur].ObjectID != temp.ObjectID {
  98. break
  99. }
  100. detail.Blocks = append(detail.Blocks, allBlocks[blksCur])
  101. }
  102. for ; pinnedsCur < len(allPinnedObjs); pinnedsCur++ {
  103. if allPinnedObjs[pinnedsCur].ObjectID != temp.ObjectID {
  104. break
  105. }
  106. detail.PinnedAt = append(detail.PinnedAt, allPinnedObjs[pinnedsCur].NodeID)
  107. }
  108. rets = append(rets, detail)
  109. }
  110. return rets, nil
  111. }
  112. func (db *ObjectDB) BatchAdd(ctx SQLContext, packageID cdssdk.PackageID, adds []coormq.AddObjectEntry) ([]cdssdk.ObjectID, error) {
  113. if len(adds) == 0 {
  114. return nil, nil
  115. }
  116. objs := make([]cdssdk.Object, 0, len(adds))
  117. for _, add := range adds {
  118. objs = append(objs, cdssdk.Object{
  119. PackageID: packageID,
  120. Path: add.Path,
  121. Size: add.Size,
  122. FileHash: add.FileHash,
  123. Redundancy: cdssdk.NewNoneRedundancy(), // 首次上传默认使用不分块的none模式
  124. CreateTime: add.UploadTime,
  125. UpdateTime: add.UploadTime,
  126. })
  127. }
  128. err := db.BatchCreateOrUpdate(ctx, objs)
  129. if err != nil {
  130. return nil, fmt.Errorf("batch create or update objects: %w", err)
  131. }
  132. pathes := make([]string, 0, len(adds))
  133. for _, add := range adds {
  134. pathes = append(pathes, add.Path)
  135. }
  136. objIDs, err := db.BatchGetPackageObjectIDs(ctx, packageID, pathes)
  137. if err != nil {
  138. return nil, fmt.Errorf("batch get object ids: %w", err)
  139. }
  140. err = db.ObjectBlock().BatchDeleteByObjectID(ctx, objIDs)
  141. if err != nil {
  142. return nil, fmt.Errorf("batch delete object blocks: %w", err)
  143. }
  144. err = db.PinnedObject().BatchDeleteByObjectID(ctx, objIDs)
  145. if err != nil {
  146. return nil, fmt.Errorf("batch delete pinned objects: %w", err)
  147. }
  148. objBlocks := make([]stgmod.ObjectBlock, 0, len(adds))
  149. for i, add := range adds {
  150. objBlocks = append(objBlocks, stgmod.ObjectBlock{
  151. ObjectID: objIDs[i],
  152. Index: 0,
  153. NodeID: add.NodeID,
  154. FileHash: add.FileHash,
  155. })
  156. }
  157. err = db.ObjectBlock().BatchCreate(ctx, objBlocks)
  158. if err != nil {
  159. return nil, fmt.Errorf("batch create object blocks: %w", err)
  160. }
  161. caches := make([]model.Cache, 0, len(adds))
  162. for _, add := range adds {
  163. caches = append(caches, model.Cache{
  164. FileHash: add.FileHash,
  165. NodeID: add.NodeID,
  166. CreateTime: time.Now(),
  167. Priority: 0,
  168. })
  169. }
  170. err = db.Cache().BatchCreate(ctx, caches)
  171. if err != nil {
  172. return nil, fmt.Errorf("batch create caches: %w", err)
  173. }
  174. return objIDs, nil
  175. }
  176. func (db *ObjectDB) BatchUpdateRedundancy(ctx SQLContext, objs []coormq.ChangeObjectRedundancyEntry) error {
  177. if len(objs) == 0 {
  178. return nil
  179. }
  180. nowTime := time.Now()
  181. objIDs := make([]cdssdk.ObjectID, 0, len(objs))
  182. dummyObjs := make([]cdssdk.Object, 0, len(objs))
  183. for _, obj := range objs {
  184. objIDs = append(objIDs, obj.ObjectID)
  185. dummyObjs = append(dummyObjs, cdssdk.Object{
  186. ObjectID: obj.ObjectID,
  187. Redundancy: obj.Redundancy,
  188. CreateTime: nowTime,
  189. UpdateTime: nowTime,
  190. })
  191. }
  192. // 目前只能使用这种方式来同时更新大量数据
  193. err := BatchNamedExec(ctx,
  194. "insert into Object(ObjectID, PackageID, Path, Size, FileHash, Redundancy, CreateTime, UpdateTime)"+
  195. " values(:ObjectID, :PackageID, :Path, :Size, :FileHash, :Redundancy, :CreateTime, :UpdateTime) as new"+
  196. " on duplicate key update Redundancy=new.Redundancy", 8, dummyObjs, nil)
  197. if err != nil {
  198. return fmt.Errorf("batch update object redundancy: %w", err)
  199. }
  200. // 删除原本所有的编码块记录,重新添加
  201. err = db.ObjectBlock().BatchDeleteByObjectID(ctx, objIDs)
  202. if err != nil {
  203. return fmt.Errorf("batch delete object blocks: %w", err)
  204. }
  205. // 删除原本Pin住的Object。暂不考虑FileHash没有变化的情况
  206. err = db.PinnedObject().BatchDeleteByObjectID(ctx, objIDs)
  207. if err != nil {
  208. return fmt.Errorf("batch delete pinned object: %w", err)
  209. }
  210. blocks := make([]stgmod.ObjectBlock, 0, len(objs))
  211. for _, obj := range objs {
  212. blocks = append(blocks, obj.Blocks...)
  213. }
  214. err = db.ObjectBlock().BatchCreate(ctx, blocks)
  215. if err != nil {
  216. return fmt.Errorf("batch create object blocks: %w", err)
  217. }
  218. caches := make([]model.Cache, 0, len(objs))
  219. for _, obj := range objs {
  220. for _, blk := range obj.Blocks {
  221. caches = append(caches, model.Cache{
  222. FileHash: blk.FileHash,
  223. NodeID: blk.NodeID,
  224. CreateTime: time.Now(),
  225. Priority: 0,
  226. })
  227. }
  228. }
  229. err = db.Cache().BatchCreate(ctx, caches)
  230. if err != nil {
  231. return fmt.Errorf("batch create object caches: %w", err)
  232. }
  233. pinneds := make([]cdssdk.PinnedObject, 0, len(objs))
  234. for _, obj := range objs {
  235. for _, p := range obj.PinnedAt {
  236. pinneds = append(pinneds, cdssdk.PinnedObject{
  237. ObjectID: obj.ObjectID,
  238. NodeID: p,
  239. CreateTime: time.Now(),
  240. })
  241. }
  242. }
  243. err = db.PinnedObject().BatchTryCreate(ctx, pinneds)
  244. if err != nil {
  245. return fmt.Errorf("batch create pinned objects: %w", err)
  246. }
  247. return nil
  248. }
  249. func (*ObjectDB) BatchDelete(ctx SQLContext, ids []cdssdk.ObjectID) error {
  250. if len(ids) == 0 {
  251. return nil
  252. }
  253. query, args, err := sqlx.In("delete from Object where ObjectID in (?)", ids)
  254. if err != nil {
  255. return err
  256. }
  257. _, err = ctx.Exec(query, args...)
  258. return err
  259. }
  260. func (*ObjectDB) DeleteInPackage(ctx SQLContext, packageID cdssdk.PackageID) error {
  261. _, err := ctx.Exec("delete from Object where PackageID = ?", packageID)
  262. return err
  263. }

本项目旨在将云际存储公共基础设施化,使个人及企业可低门槛使用高效的云际存储服务(安装开箱即用云际存储客户端即可,无需关注其他组件的部署),同时支持用户灵活便捷定制云际存储的功能细节。