@@ -56,21 +56,47 @@ export const calculatePeriodUsage = async (instruction, ctx) => {
5656 console . log ( `Customer: ${ instruction . customer } ` )
5757 console . log ( `Period: ${ instruction . from . toISOString ( ) } - ${ instruction . to . toISOString ( ) } ` )
5858
59+ // Try to get snapshot at exact 'from' date first
5960 const { ok : snap , error } = await ctx . spaceSnapshotStore . get ( {
6061 space : instruction . space ,
6162 provider : instruction . provider ,
6263 recordedAt : instruction . from
6364 } )
6465 if ( error && error . name !== 'RecordNotFound' ) return { error }
65- if ( ! snap ) console . warn ( `!!! Snapshot not found, assuming empty space !!!` )
6666
67- let size = snap ?. size ?? 0n
68- let usage = size * BigInt ( instruction . to . getTime ( ) - instruction . from . getTime ( ) ) // initial usage from snapshot
67+ let snapshotToUse = snap
68+ let snapshotDate = instruction . from
69+
70+ // If no snapshot at exact 'from' date, list snapshots in descending order (newest first)
71+ // and check if the most recent one is before 'from'.
72+ if ( ! snap ) {
73+ console . warn ( `No snapshot found at ${ instruction . from . toISOString ( ) } , querying for most recent snapshot before this date...` )
74+
75+ const listResult = await ctx . spaceSnapshotStore . list ( {
76+ space : instruction . space ,
77+ provider : instruction . provider
78+ } , { size : 1 , scanIndexForward : false } ) // get newest snapshot
79+
80+ if ( listResult . error ) return listResult
81+
82+ // Check if the newest snapshot is at or before 'from'
83+ const newestSnapshot = listResult . ok . results [ 0 ]
84+ if ( newestSnapshot && newestSnapshot . recordedAt . getTime ( ) <= instruction . from . getTime ( ) ) {
85+ snapshotToUse = newestSnapshot
86+ snapshotDate = newestSnapshot . recordedAt
87+ console . log ( `Found snapshot @ ${ snapshotDate . toISOString ( ) } : ${ newestSnapshot . size } bytes` )
88+ } else {
89+ console . warn ( `!!! No snapshot found before ${ instruction . from . toISOString ( ) } , assuming empty space !!!` )
90+ }
91+ }
92+
93+ let size = snapshotToUse ? snapshotToUse . size : 0n
94+ let usage = size * BigInt ( instruction . to . getTime ( ) - snapshotDate . getTime ( ) ) // initial usage from snapshot
6995
70- console . log ( `Total size of ${ instruction . space } is ${ size } bytes @ ${ instruction . from . toISOString ( ) } ` )
96+ console . log ( `Starting calculation from ${ snapshotDate . toISOString ( ) } : ${ size } bytes for ${ instruction . space } ` )
7197
7298 let totalDiffs = 0
73- for await ( const page of iterateSpaceDiffs ( instruction , ctx ) ) {
99+ for await ( const page of iterateSpaceDiffs ( { ... instruction , from : snapshotDate } , ctx ) ) {
74100 if ( page . error ) return page
75101 totalDiffs += page . ok . length
76102 for ( const diff of page . ok ) {
0 commit comments