@adobe/helix-admin-support 5.0.3 → 5.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,3 +1,10 @@
1
+ # [5.1.0](https://github.com/adobe/helix-admin-support/compare/v5.0.3...v5.1.0) (2026-01-21)
2
+
3
+
4
+ ### Features
5
+
6
+ * media log support functions ([#485](https://github.com/adobe/helix-admin-support/issues/485)) ([0e98f0f](https://github.com/adobe/helix-admin-support/commit/0e98f0f91ae042b482dbb8c3f6cd43d37b3e1280))
7
+
1
8
  ## [5.0.3](https://github.com/adobe/helix-admin-support/compare/v5.0.2...v5.0.3) (2025-11-03)
2
9
 
3
10
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@adobe/helix-admin-support",
3
- "version": "5.0.3",
3
+ "version": "5.1.0",
4
4
  "description": "Helix Admin Support Library",
5
5
  "main": "src/index.js",
6
6
  "type": "module",
@@ -45,26 +45,25 @@
45
45
  "@smithy/node-http-handler": "^4.0.0"
46
46
  },
47
47
  "devDependencies": {
48
- "@adobe/eslint-config-helix": "3.0.12",
49
- "@adobe/jsonschema2md": "8.0.7",
50
- "@eslint/config-helpers": "0.4.0",
48
+ "@adobe/eslint-config-helix": "3.0.16",
49
+ "@adobe/jsonschema2md": "8.0.10",
50
+ "@eslint/config-helpers": "0.5.0",
51
51
  "@semantic-release/changelog": "6.0.3",
52
52
  "@semantic-release/git": "10.0.1",
53
- "@semantic-release/npm": "13.0.0",
54
53
  "c8": "10.1.3",
55
54
  "eslint": "9.4.0",
56
55
  "husky": "9.1.7",
57
56
  "jsdoc-to-markdown": "9.1.3",
58
57
  "json-schema-to-typescript": "15.0.4",
59
58
  "junit-report-builder": "5.1.1",
60
- "lint-staged": "16.2.4",
61
- "mocha": "11.7.4",
59
+ "lint-staged": "16.2.7",
60
+ "mocha": "11.7.5",
62
61
  "mocha-multi-reporters": "1.5.1",
63
62
  "mocha-suppress-logs": "0.6.0",
64
63
  "nock": "13.5.6",
65
- "semantic-release": "25.0.0",
64
+ "semantic-release": "25.0.2",
66
65
  "xml2js": "0.6.2",
67
- "yaml": "2.8.1"
66
+ "yaml": "2.8.2"
68
67
  },
69
68
  "lint-staged": {
70
69
  "*.js": "eslint",
package/src/index.js CHANGED
@@ -24,3 +24,4 @@ export * from './flatJson2Object.js';
24
24
  export * from './BatchedQueueClient.js';
25
25
  export * from './UpdatesPartitioner.js';
26
26
  export * from './auditlog/AuditLog.js';
27
+ export * from './medialog/MediaLog.js';
@@ -0,0 +1,50 @@
1
+ /*
2
+ * Copyright 2025 Adobe. All rights reserved.
3
+ * This file is licensed to you under the Apache License, Version 2.0 (the "License");
4
+ * you may not use this file except in compliance with the License. You may obtain a copy
5
+ * of the License at http://www.apache.org/licenses/LICENSE-2.0
6
+ *
7
+ * Unless required by applicable law or agreed to in writing, software distributed under
8
+ * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
9
+ * OF ANY KIND, either express or implied. See the License for the specific language
10
+ * governing permissions and limitations under the License.
11
+ */
12
+
13
+ import MediaLogReader from './Reader.js';
14
+ import { resolveOptions } from './utils.js';
15
+ import MediaLogWriter from './Writer.js';
16
+
17
+ /**
18
+ * @typedef {{
19
+ * bucketName?: string;
20
+ * }} Options
21
+ */
22
+
23
+ /**
24
+ * Create a media log reader for a content bus.
25
+ *
26
+ * @param {String} contentBusId content bus identifier
27
+ * @param {Logger} log logger
28
+ * @param {Options} [opts] options
29
+ * @returns {MediaLogReader} reader
30
+ */
31
+ function createReader(contentBusId, log, opts) {
32
+ return new MediaLogReader(contentBusId, log, resolveOptions(opts));
33
+ }
34
+
35
+ /**
36
+ * Create a media log writer for a content bus.
37
+ *
38
+ * @param {String} contentBusId content bus identifier
39
+ * @param {Logger} log logger
40
+ * @param {Options} [opts] options
41
+ * @returns {MediaLogWriter} writer
42
+ */
43
+ function createWriter(contentBusId, log, opts) {
44
+ return new MediaLogWriter(contentBusId, log, resolveOptions(opts));
45
+ }
46
+
47
+ export const MediaLog = {
48
+ createReader,
49
+ createWriter,
50
+ };
@@ -0,0 +1,283 @@
1
+ /*
2
+ * Copyright 2025 Adobe. All rights reserved.
3
+ * This file is licensed to you under the Apache License, Version 2.0 (the "License");
4
+ * you may not use this file except in compliance with the License. You may obtain a copy
5
+ * of the License at http://www.apache.org/licenses/LICENSE-2.0
6
+ *
7
+ * Unless required by applicable law or agreed to in writing, software distributed under
8
+ * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
9
+ * OF ANY KIND, either express or implied. See the License for the specific language
10
+ * governing permissions and limitations under the License.
11
+ */
12
+
13
+ import { promisify } from 'util';
14
+ import zlib from 'zlib';
15
+ import { GetObjectCommand, S3Client } from '@aws-sdk/client-s3';
16
+ import { Response } from '@adobe/fetch';
17
+ import { INDEX_FILE } from './utils.js';
18
+ import DateFormat from '../auditlog/DateFormat.js';
19
+
20
+ const gunzip = promisify(zlib.gunzip);
21
+
22
+ /**
23
+ * @typedef LogLocation
24
+ * @property {number} fileIndex file index into log file array
25
+ * @property {number} entryIndex entry index into entries array of that log file
26
+ *
27
+ * @typedef LogEntries
28
+ * @property {number} fileIndex file index into log file array
29
+ * @property {number} entryIndex entry index into entries array of that log file
30
+ * @property {MediaLogEntry[]} entries log entry
31
+ *
32
+ * @typedef LogResult
33
+ * @property {MediaLogEntry[]} entries log entry
34
+ * @property {string} nextToken optional next token
35
+ *
36
+ * @typedef MediaLogEntry
37
+ * @property {number} timestamp timestamp in milliseconds
38
+ * @property {string} operation operation type (ingest, reuse, delete, etc.)
39
+ * @property {string} mediaHash media hash identifier
40
+ * @property {string} contentType MIME type
41
+ * @property {string} user user email or identifier
42
+ * @property {string} path storage/reference path
43
+ * @property {string} [originalFilename] original file name
44
+ * @property {string} [contentSourceType] source system
45
+ */
46
+
47
+ /**
48
+ * Return a slice of entries that don't exceed a given size
49
+ * @param {number|undefined} maxSize maximum size
50
+ * @param {MediaLogEntry[]} obj.entries entries
51
+ * @param {number} obj.fileIndex file index
52
+ * @param {number} obj.entryIndex entry index
53
+ * @param {object} next next iterator to return unless we exceed the maximum size
54
+ * @returns {MediaLogEntry[]} slice of entries
55
+ */
56
+ function checkSize(maxSize, {
57
+ entries, fileIndex, entryIndex, next,
58
+ }) {
59
+ if (maxSize && JSON.stringify(entries).length >= maxSize) {
60
+ let totalSize = 2;
61
+ for (const [index, entry] of entries.entries()) {
62
+ totalSize += JSON.stringify(entry).length + 1;
63
+ if (totalSize > maxSize) {
64
+ // return at least one item
65
+ const count = Math.max(1, index);
66
+ return {
67
+ entries: entries.slice(0, count),
68
+ next: { fileIndex, entryIndex: entryIndex + count },
69
+ };
70
+ }
71
+ }
72
+ /* c8 ignore next */
73
+ }
74
+ return next ? { entries, next } : { entries };
75
+ }
76
+
77
+ /**
78
+ * Media log reader implemented in S3.
79
+ */
80
+ export default class Reader {
81
+ /**
82
+ * @param {string} contentBusId content bus identifier
83
+ * @param {import('@adobe/helix-universal').Logger} log logger
84
+ * @param {Required<import('./MediaLog.js').Options>} opts options
85
+ */
86
+ constructor(contentBusId, log, opts) {
87
+ this.prefix = contentBusId;
88
+ this.log = log;
89
+ this.bucketName = opts.bucketName;
90
+ }
91
+
92
+ /**
93
+ * Initialize this log, retrieves the list of log files available.
94
+ */
95
+ async init() {
96
+ this.s3 = new S3Client({});
97
+
98
+ const { prefix } = this;
99
+
100
+ try {
101
+ const res = await this.s3.send(new GetObjectCommand({
102
+ Bucket: this.bucketName,
103
+ Key: `${prefix}/${INDEX_FILE}`,
104
+ }));
105
+ const logContents = await new Response(res.Body, {}).text();
106
+ this.logFiles = logContents.split('\n').map((name) => ({
107
+ name,
108
+ timestamp: DateFormat.parse(name).getTime(),
109
+ }));
110
+ } catch (e) {
111
+ /* c8 ignore next 3 */
112
+ if (e.$metadata?.httpStatusCode !== 404) {
113
+ throw e;
114
+ }
115
+ this.logFiles = [];
116
+ }
117
+ return this;
118
+ }
119
+
120
+ /**
121
+ * Read the log contents of a log file from S3.
122
+ *
123
+ * @param {number} fileIndex file index
124
+ *
125
+ * @returns {Promise<MediaLogEntry[]>} array of entries
126
+ */
127
+ async #getLogContents(fileIndex) {
128
+ const {
129
+ prefix, logFiles, s3, log,
130
+ } = this;
131
+
132
+ const key = `${prefix}/${logFiles[fileIndex].name}.gz`;
133
+ try {
134
+ const res = await s3.send(new GetObjectCommand({
135
+ Bucket: this.bucketName,
136
+ Key: key,
137
+ }));
138
+ const buf = await new Response(res.Body, {}).buffer();
139
+ return JSON.parse(await gunzip(buf));
140
+ } catch (e) {
141
+ log.debug(e);
142
+ throw new Error(`Unable to find media log file '${key}': ${e.message}`);
143
+ }
144
+ }
145
+
146
+ /**
147
+ * Find entries starting at a given date.
148
+ *
149
+ * @param {number} after timestamp
150
+ *
151
+ * @returns {Promise<LogEntries>} entries, fileIndex and entryIndex
152
+ */
153
+ async #findEntries(after) {
154
+ const { logFiles } = this;
155
+
156
+ // stop if there are no log files at all
157
+ if (logFiles.length === 0) {
158
+ return { entries: [] };
159
+ }
160
+
161
+ // find the last log file that started before the given date
162
+ const fileIndex = logFiles.findLastIndex(({ timestamp }) => timestamp <= after);
163
+ if (fileIndex === -1) {
164
+ // none found, so return the very first log file
165
+ return { entries: await this.#getLogContents(0), fileIndex: 0, entryIndex: 0 };
166
+ }
167
+
168
+ // we found a log file that was created earlier, so locate the first entry that started
169
+ // at or after the given date
170
+ let entries = await this.#getLogContents(fileIndex);
171
+
172
+ const entryIndex = entries.findIndex(({ timestamp }) => timestamp >= after);
173
+ if (entryIndex !== -1) {
174
+ // found: so return that slice
175
+ return { entries: entries.slice(entryIndex), fileIndex, entryIndex };
176
+ }
177
+
178
+ // the log file found stops before the date given, so start at next one
179
+ if (fileIndex === logFiles.length - 1) {
180
+ // there is no next log file
181
+ return { entries: [] };
182
+ }
183
+
184
+ entries = await this.#getLogContents(fileIndex + 1);
185
+ return { entries, fileIndex: fileIndex + 1, entryIndex: 0 };
186
+ }
187
+
188
+ /**
189
+ * Locate entries given a previously saved location
190
+ *
191
+ * @param {LogLocation} location location
192
+ * @returns {Promise<LogEntries>} entries, fileIndex and entryIndex
193
+ */
194
+ async #locateEntries(location) {
195
+ const { log, logFiles } = this;
196
+
197
+ const { fileIndex, entryIndex } = location;
198
+ if (!Number.isInteger(fileIndex) || !Number.isInteger(entryIndex)) {
199
+ log.warn(`Next file and entry index are not numbers: ${fileIndex}/${entryIndex}`);
200
+ return { entries: [] };
201
+ }
202
+ if (fileIndex < 0 || fileIndex >= logFiles.length) {
203
+ log.warn(`Next file index (${fileIndex}) out of log files range: ${logFiles.length}`);
204
+ return { entries: [] };
205
+ }
206
+ const entries = await this.#getLogContents(fileIndex);
207
+ if (entryIndex < 0 || entryIndex >= entries.length) {
208
+ log.warn(`Next entry index (${entryIndex}) out of entries range: ${entries.length}`);
209
+ return { entries: [] };
210
+ }
211
+ return { entries: entries.slice(entryIndex), fileIndex, entryIndex };
212
+ }
213
+
214
+ /**
215
+ * Lookup entries that lie between two timestamps
216
+ *
217
+ * @param {number} after from timestamp
218
+ * @param {number} before to timestamp
219
+ * @param {number} limit number of entries to return at most
220
+ * @param {number} maxSize maximum total size of entries when stringified
221
+ * @param {LogLocation} location optional location with `fileIndex` and `entryIndex`
222
+ *
223
+ * @returns {Promise<LogResult>} log result
224
+ */
225
+ async getEntries(after, before, { limit, maxSize }, location) {
226
+ const { logFiles } = this;
227
+ const { entries, fileIndex, entryIndex } = location
228
+ ? await this.#locateEntries(location)
229
+ : await this.#findEntries(after);
230
+
231
+ if (entries.length === 0) {
232
+ // no entries found at all, stop here to keep the following simpler
233
+ return { entries };
234
+ }
235
+
236
+ // find the utmost limit of items to return
237
+ let remaining = entries.findIndex(({ timestamp }) => timestamp > before);
238
+ if (remaining === -1) {
239
+ remaining = entries.length;
240
+ }
241
+
242
+ // return either `limit` number of items, or items left in that file, whichever is smaller
243
+ const count = Math.min(limit, remaining);
244
+ if (count < remaining) {
245
+ // `limit` was reached first, so continue after that
246
+ return checkSize(maxSize, {
247
+ entries: entries.slice(0, count),
248
+ fileIndex,
249
+ entryIndex,
250
+ next: { fileIndex, entryIndex: entryIndex + count },
251
+ });
252
+ }
253
+ if (remaining < entries.length) {
254
+ // `before` timestamp was reached first, so stop
255
+ return checkSize(maxSize, {
256
+ entries: entries.slice(0, count),
257
+ fileIndex,
258
+ entryIndex,
259
+ });
260
+ }
261
+
262
+ // we return all items in this file, and need to determine whether to continue paging
263
+ if (fileIndex === logFiles.length - 1 || logFiles[fileIndex + 1].timestamp > before) {
264
+ // there's no next page or it starts after `before` date, so stop
265
+ return checkSize(maxSize, {
266
+ entries,
267
+ fileIndex,
268
+ entryIndex,
269
+ });
270
+ }
271
+ // next location will start at the beginning of the next file
272
+ return checkSize(maxSize, {
273
+ entries,
274
+ fileIndex,
275
+ entryIndex,
276
+ next: { fileIndex: fileIndex + 1, entryIndex: 0 },
277
+ });
278
+ }
279
+
280
+ close() {
281
+ this.s3.destroy();
282
+ }
283
+ }
@@ -0,0 +1,191 @@
1
+ /*
2
+ * Copyright 2025 Adobe. All rights reserved.
3
+ * This file is licensed to you under the Apache License, Version 2.0 (the "License");
4
+ * you may not use this file except in compliance with the License. You may obtain a copy
5
+ * of the License at http://www.apache.org/licenses/LICENSE-2.0
6
+ *
7
+ * Unless required by applicable law or agreed to in writing, software distributed under
8
+ * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
9
+ * OF ANY KIND, either express or implied. See the License for the specific language
10
+ * governing permissions and limitations under the License.
11
+ */
12
+
13
+ import crypto from 'crypto';
14
+ import { promisify } from 'util';
15
+ import zlib from 'zlib';
16
+ import { GetObjectCommand, PutObjectCommand, S3Client } from '@aws-sdk/client-s3';
17
+ import { Response } from '@adobe/fetch';
18
+ import { INDEX_FILE } from './utils.js';
19
+ import DateFormat from '../auditlog/DateFormat.js';
20
+
21
+ const gzip = promisify(zlib.gzip);
22
+ const gunzip = promisify(zlib.gunzip);
23
+
24
+ /**
25
+ * Metadata property for last event in log file. We update that property
26
+ * whenever we store events to a log file.
27
+ */
28
+ const META_LAST_EVENT = 'last-event-time';
29
+
30
+ /**
31
+ * Threshold size to allow in one log file.
32
+ */
33
+ const MAX_OBJECT_SIZE = 512 * 1024;
34
+
35
+ /**
36
+ * Generate log file from date and some random value.
37
+ *
38
+ * @returns log file, consisting of name and date created
39
+ */
40
+ function generateID() {
41
+ return `${DateFormat.format(new Date())}-${crypto.randomBytes(8).toString('hex').toUpperCase()}`;
42
+ }
43
+
44
+ /**
45
+ * Media log writer implemented in S3
46
+ */
47
+ export default class Writer {
48
+ /**
49
+ * @param {string} contentBusId content bus identifier
50
+ * @param {Logger} log logger
51
+ * @param {Required<import('./MediaLog.js').Options>} opts options
52
+ */
53
+ constructor(contentBusId, log, opts) {
54
+ this.prefix = contentBusId;
55
+ this.log = log;
56
+ this.bucketName = opts.bucketName;
57
+ }
58
+
59
+ /**
60
+ * Initialize this log.
61
+ */
62
+ async init() {
63
+ this.s3 = new S3Client({});
64
+ return this;
65
+ }
66
+
67
+ /**
68
+ * Fetch index file
69
+ *
70
+ * @returns {Promise<String[]>} log entry file names array
71
+ */
72
+ async #fetchIndex() {
73
+ const { prefix, s3 } = this;
74
+
75
+ // fetch name of last log object
76
+ try {
77
+ const res = await s3.send(new GetObjectCommand({
78
+ Bucket: this.bucketName,
79
+ Key: `${prefix}/${INDEX_FILE}`,
80
+ }));
81
+ const logContents = await new Response(res.Body, {}).text();
82
+ return logContents.split('\n');
83
+ } catch (e) {
84
+ /* c8 ignore next 3 */
85
+ if (e.$metadata.httpStatusCode !== 404) {
86
+ throw e;
87
+ }
88
+ }
89
+ return [];
90
+ }
91
+
92
+ /**
93
+ * Fetch log file. Returns null if the log file is not found or too large to accomodate
94
+ * another record.
95
+ *
96
+ * @param {string} key
97
+ */
98
+ async #fetchLogFile(key) {
99
+ const { s3 } = this;
100
+
101
+ try {
102
+ const res = await s3.send(new GetObjectCommand({
103
+ Bucket: this.bucketName,
104
+ Key: `${key}.gz`,
105
+ }));
106
+ if (res.ContentLength < MAX_OBJECT_SIZE) {
107
+ const buf = await new Response(res.Body, {}).buffer();
108
+ return { key, contents: JSON.parse(await gunzip(buf)) };
109
+ }
110
+ } catch (e) {
111
+ /* c8 ignore next 3 */
112
+ if (e.$metadata.httpStatusCode !== 404) {
113
+ throw e;
114
+ }
115
+ }
116
+ return null;
117
+ }
118
+
119
+ /**
120
+ * Retrieves the last log object or creates one if necessary.
121
+ *
122
+ * @returns an object containing a key and contents
123
+ */
124
+ async #getOrCreateLogObject() {
125
+ const { prefix, s3 } = this;
126
+
127
+ // fetch list of log files
128
+ const logFiles = await this.#fetchIndex();
129
+
130
+ // fetch contents of last log object
131
+ if (logFiles.length) {
132
+ const key = `${prefix}/${logFiles[logFiles.length - 1]}`;
133
+ const logFile = await this.#fetchLogFile(key);
134
+ if (logFile) {
135
+ return logFile;
136
+ }
137
+ }
138
+
139
+ // generate new last log object, store modified list in index
140
+ logFiles.push(generateID());
141
+ await s3.send(new PutObjectCommand({
142
+ Body: logFiles.join('\n'),
143
+ Bucket: this.bucketName,
144
+ ContentType: 'text/plain',
145
+ Key: `${prefix}/${INDEX_FILE}`,
146
+ }));
147
+ return { key: `${prefix}/${logFiles[logFiles.length - 1]}`, contents: [] };
148
+ }
149
+
150
+ /**
151
+ * Store a modified log file back to S3
152
+ *
153
+ * @param {string} key key for object to store, with project prefix
154
+ * @param {string} contents contents to store
155
+ * @param {object} metadata metadata to store to log file
156
+ */
157
+ async #storeLogFile(key, contents, metadata) {
158
+ const { s3 } = this;
159
+ await s3.send(new PutObjectCommand({
160
+ Body: await gzip(JSON.stringify(contents)),
161
+ Bucket: this.bucketName,
162
+ ContentEncoding: 'gzip',
163
+ ContentType: 'application/json',
164
+ Key: `${key}.gz`,
165
+ Metadata: metadata,
166
+ }));
167
+ }
168
+
169
+ /**
170
+ * Appends rows to the media log
171
+ *
172
+ * @param {Array} updates added rows
173
+ * @returns {Promise<String>} name of log file where updates have been written to
174
+ */
175
+ async append(updates) {
176
+ if (updates.length) {
177
+ const { key, contents } = await this.#getOrCreateLogObject();
178
+ const lastEventTime = updates[updates.length - 1].timestamp;
179
+ contents.push(...updates);
180
+ await this.#storeLogFile(key, contents, {
181
+ [META_LAST_EVENT]: DateFormat.format(new Date(lastEventTime)),
182
+ });
183
+ return key;
184
+ }
185
+ return null;
186
+ }
187
+
188
+ close() {
189
+ this.s3.destroy();
190
+ }
191
+ }
@@ -0,0 +1,32 @@
1
+ /*
2
+ * Copyright 2025 Adobe. All rights reserved.
3
+ * This file is licensed to you under the Apache License, Version 2.0 (the "License");
4
+ * you may not use this file except in compliance with the License. You may obtain a copy
5
+ * of the License at http://www.apache.org/licenses/LICENSE-2.0
6
+ *
7
+ * Unless required by applicable law or agreed to in writing, software distributed under
8
+ * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
9
+ * OF ANY KIND, either express or implied. See the License for the specific language
10
+ * governing permissions and limitations under the License.
11
+ */
12
+
13
+ // Re-export INDEX_FILE from auditlog since it's the same constant
14
+ export { INDEX_FILE } from '../auditlog/utils.js';
15
+
16
+ /**
17
+ * Bucket to use for media logging.
18
+ */
19
+ const DEFAULT_BUCKET_NAME = 'helix-media-logs';
20
+
21
+ /**
22
+ * Resolve options object to contain all properties.
23
+ *
24
+ * @param {import("./MediaLog").Options} [opts]
25
+ * @returns {Required<import("./MediaLog").Options>}
26
+ */
27
+ export function resolveOptions(opts = {}) {
28
+ return {
29
+ bucketName: DEFAULT_BUCKET_NAME,
30
+ ...opts,
31
+ };
32
+ }