Edge Developer Platform
  • Edge Functions
    • Overview
    • Getting Started
    • Operation Guide
      • Function Management
      • Web Debugging
      • Function Trigger
      • Environment Variable
      • Code Replica
    • Runtime APIs
      • addEventListener
      • Cache
      • Cookies
      • Encoding
      • Fetch
      • FetchEvent
      • Headers
      • Request
      • Response
      • Streams
        • ReadableStream
        • ReadableStreamBYOBReader
        • ReadableStreamDefaultReader
        • TransformStream
        • WritableStream
        • WritableStreamDefaultWriter
      • Web Crypto
      • Web standards
      • Images
        • ImageProperties
    • Sample Functions
      • Example Overview
      • Obtaining Client URL Information
      • Customization Based on Client Geo Location
      • Obtaining Client Geo Location Information
      • Batch Redirect
      • URL rewrite based on regular expressions
      • Returning an HTML Page
      • Returning a JSON Object
      • Fetch Remote Resources
      • Authenticating a Request Header
      • Modifying a Response Header
      • Performing an A/B Test
      • Setting Cookies
      • Performing Redirect Based on the Request Location
      • Using the Cache API
      • Caching POST Requests
      • Responding in Streaming Mode
      • Merging Resources and Responding in Streaming Mode
      • Protecting Data from Tampering
      • Rewriting a m3u8 File and Configuring Authentication
      • Adaptive Image Resize
      • Image Adaptive WebP
      • Customize Referer restriction rules
      • Remote Authentication
      • HMAC Digital Signature
      • Naming a Downloaded File
      • Obtaining Client IP Address
      • Complex origin-pull URL rewriting
      • Web Bot Auth
    • Practical Tutorial
      • Overview
      • Origin retrieval based on user IP/geographic location
        • EdgeOne Implementation of Session Persistence Based on Client IP Addresses
        • EdgeOne Implementation of Origin-Pull Based on Client's Geo Location
      • APK dynamic packaging
        • EdgeOne enables dynamic packaging of Android APKs.
          • Feature Overview
          • Step 1: Preprocess the Android APK Parent Package
          • Step 2: Write the Channel Information into the APK Package with EdgeOne Edge Functions
      • Canary Release and Region-specific Execution
      • Adaptive Image Format Conversion via Edge Functions
      • Two Ways to Implement CDN Origin-pull Via Edge Function: Fetch and Passthrough
  • KV Storage
    • Overview
    • Operation Guide
  • Edge reasoning
    • Edge Inference Overview
    • Quick Guide

Step 2: Write the Channel Information into the APK Package with EdgeOne Edge Functions

With EdgeOne edge functions, we can dynamically write channel information into the APK package. Users only need to access the domain bound to the edge function and configure the trigger to invoke the edge function, thereby enabling dynamic packaging and accelerated distribution of APKs.

Step 1: Adding an Acceleration Domain Name for Accelerated Delivery

Add an acceleration domain by following the instructions in Adding an Acceleration Domain. For example, use www.example.com and set the origin server to the custom COS domain where the Android APK master package is stored. For details, see Switching a Bucket to a Custom Domain. The configuration is shown in the following figure:



Note:
This domain will be used to access and download the APK installation package.

Step 2: Creating an Edge Function for Triggering Channel Information Writing

1. Create an edge function by following the instructions in Function Management, and copy the following code into the function code.
Note:
This function has been updated to support single-Range requests, making it suitable for segmented download scenarios such as multi-threaded downloaders and resumable downloads. Previously, Range requests were passed through directly to the origin without writing channel information. After the update, channel information can be written normally.
Three single-Range formats are supported: bytes=start-end, bytes=start-, and bytes=-suffix. When the requested Range overlaps with the channel information write area, channel information is still written correctly, and 206 Partial Content is returned with the correct Content-Length and Content-Range. If the Range request cannot be satisfied, 416 Range Not Satisfiable is returned.
Responses to non-Range requests carry Accept-Ranges: bytes, allowing downloaders to detect and enable segmented downloads.
Multi-Range requests (such as bytes=0-99,200-299) are not supported yet. Such requests are passed through directly to the origin, and channel information is not written. The multi-threaded segmentation used by common downloaders consists of multiple concurrent single-Range requests, which are not affected by this limitation.
const CUSTOM_BLOCK_VALUE_LENGTH = 10240;
const APK_SIGNING_BLOCK_MAGIC_LENGTH = 16;
const APK_SIGNING_BLOCK_OFFSET_LENGTH = 8;

const APK_COMMENT_LENGTH = 512;

class EdgePack {
totalSize;
signVersion;
centralDirectoryOffset;
customBlockValueStart;
customBlockValueEnd;
rangeRelativeOffset;
customInfo;

constructor() {
/** @type {number} */
this.totalSize = null;
this.signVersion = null;
this.centralDirectoryOffset = null;
this.customBlockValueStart = null;
this.customBlockValueEnd = null;
this.rangeRelativeOffset = null;
/** @type {string} */
this.customInfo = null;
/** @type {string} */
this.customName = null;
/** @type {number[]} */
this.customRange = null;
/** @type {boolean} */
this.invalidRange = false; // Mark whether it is an invalid Range
}

async handle(event) {
const { request } = event;

const headers = new Headers(request.headers);

const modifiedRequest = new Request(request, { headers });

if (!this.checkRequest(modifiedRequest)) {
// If an invalid Range format is detected, return 416 directly
if (this.invalidRange) {
const responseHeaders = new Headers();
// At this point, totalSize has not been obtained yet, so Content-Range cannot be set
// responseHeaders.set("Content-Range", `bytes */0`);
return event.respondWith(
new Response("", {
status: 416,
statusText: "Range Not Satisfiable",
headers: responseHeaders,
})
);
}
// In other cases, passthrough
return;
}

let response = null;
try {
const headHeaders = new Headers(modifiedRequest.headers);
// Delete the Range header to obtain the correct Content-Length
headHeaders.delete("Range");

const headRequest = new Request(modifiedRequest.url, {
method: "HEAD",
headers: headHeaders,
});
response = await fetch(headRequest, { redirect: "manual" });
} catch (err) {
const error = {
code: "FETCH_ORIGIN_ERROR",
message: err?.message,
};
response = new Response(JSON.stringify(error), {
status: 590,
});
}

if (!this.checkResponse(response)) {
// If it is an invalid Range (format error or range error), return the 416 status code
if (this.invalidRange && this.totalSize !== null) {
const headers = new Headers();
headers.set("Content-Range", `bytes */${this.totalSize}`);
return event.respondWith(
new Response("", {
status: 416,
statusText: "Range Not Satisfiable",
headers: headers,
})
);
}
return event.respondWith(response);
}

if (!!this.customName) {
response.headers.set(
"Content-Disposition",
`attachment; filename="${this.customName}"`
);
}

// Handle a single-range Range request
if (this.customRange) {
const [rangeStart, rangeEnd] = this.customRange;

let actualStart = rangeStart;
let actualEnd = rangeEnd;
let contentLength = this.totalSize;

if (rangeStart === null && rangeEnd !== null) {
// bytes=-suffix format: the last suffix bytes
actualStart = Math.max(0, this.totalSize - rangeEnd);
actualEnd = this.totalSize - 1;
contentLength = Math.min(rangeEnd, this.totalSize);
} else if (rangeEnd !== null) {
// bytes=start-end format
contentLength = rangeEnd - rangeStart + 1;
actualEnd = rangeEnd;
} else if (rangeStart !== null) {
// bytes=start- format
actualEnd = this.totalSize - 1;
contentLength = this.totalSize - rangeStart;
}

response.headers.set(
"Content-Range",
`bytes ${actualStart}-${actualEnd}/${this.totalSize}`
);
response.headers.set("Content-Length", contentLength.toString());
response.headers.set("Accept-Ranges", "bytes");
response = new Response(null, {
status: 206,
statusText: "Partial Content",
headers: response.headers,
});
}
// Handle non-Range requests
else {
// Non-Range requests should also declare support for Range
response.headers.set("Accept-Ranges", "bytes");
}

const streamResponse = new Response(
await this.combineStreams(modifiedRequest),
response
);

return event.respondWith(streamResponse);
}

getRelativeOffset(response) {
const start = this.customBlockValueStart;
const end = this.customBlockValueEnd;

const range = response.headers.get("Content-Range");

if (!range) return start;

const match = range.match(/bytes\s*(\d*)-(\d*)/i);
if (!match || match?.length < 2) {
return start;
}

const rangeStart = +match[1];
const rangeEnd = +match[2];

if (rangeEnd < start || rangeStart > end) {
return null;
}

return start - rangeStart;
}

checkRequest(request) {
if (request.method !== "GET") {
// For non-GET requests, use passthrough for origin-pull
return false;
}

if (request.headers.has("Range")) {
const range = request.headers.get("Range");

// Check whether it is a multi-range request
if (range.includes(",")) {
// For Multi-Range requests, use passthrough for origin-pull
console.log("Multi-Range detected, using passthrough");
return false;
}
// Single Range request
else {
// Use more precise regex: match bytes=start-end and bytes=-suffix separately
// Capture groups: (1) start (2) end for the start-end format
// (3) suffix for the -suffix format
const match = range.match(/bytes=(?:(\d+)-(\d*)|-(\d+))$/i);

if (match) {
// Handle three Range formats:
// 1. bytes=start-end: specified range
// 2. bytes=start-: from start to the end of the file
// 3. bytes=-suffix: the last suffix bytes

// Check whether it is in the bytes=-suffix format (the third capture group has a value)
if (match[3] !== undefined) {
// bytes=-suffix format: the last suffix bytes
const suffix = +match[3];

// bytes=-0 is an invalid range request and should return 416
if (suffix === 0) {
console.warn("Invalid Range: bytes=-0 is not satisfiable");
this.invalidRange = true;
return false;
}

this.customRange = [null, suffix];
} else {
// bytes=start-end or bytes=start- format
const start = match[1] ? +match[1] : null;
const end = match[2] && match[2] !== "" ? +match[2] : null;

// Detect the invalid case where start > end
if (start !== null && end !== null && start > end) {
console.warn("Invalid Range: start > end:", range);
this.invalidRange = true;
return false;
}

this.customRange = [start, end];
}
} else {
console.warn("Invalid Range format:", range);
this.invalidRange = true;
return false;
}
}
}

const { pathname, searchParams } = new URL(request.url);

// Obtain the channel information parameter, which is stored in the comment parameter
const comment = searchParams?.get("comment");

// For non-APK files or when there is no channel information parameter, use passthrough for origin-pull
if (!pathname.endsWith(".apk") || !comment) {
return false;
}

this.customInfo = comment;

const filename = searchParams?.get("filename");

if (filename) {
this.customName = filename;
}

return true;
}

/**
* @param {number} fileSize
* @returns {boolean}
*/
validateRange(fileSize) {
// Verify a single Range
if (!this.customRange) {
return true;
}

const [rangeStart, rangeEnd] = this.customRange;

// Process the bytes=-suffix format
if (rangeStart === null && rangeEnd !== null) {
// If suffix exceeds the file size, correct it to the file size
if (rangeEnd > fileSize) {
this.customRange = [null, fileSize];
return true;
}
return true;
}

// Process the bytes=start-end and bytes=start- formats
if (rangeStart !== null) {
// If start exceeds the file size range, mark it as invalid and return false
if (rangeStart >= fileSize) {
this.invalidRange = true;
return false;
}

// If start is within the range but end exceeds the range, correct it to start-
if (rangeEnd !== null && rangeEnd >= fileSize) {
this.customRange = [rangeStart, null];
return true;
}
}

return true;
}

checkResponse(response) {
if (response.status !== 200 && response.status !== 206) {
return false;
}

const contentLength = response.headers.get("Content-Length");

if (response.body === null || contentLength === null) {
return false;
}

this.totalSize = Number(contentLength);

if (this.customRange && !this.validateRange(this.totalSize)) {
// If the Range request exceeds the range, mark invalidRange and return false
// invalidRange has been set in validateRange()
return false;
}

const cosOffsetHeader = response.headers.get("x-cos-meta-edgepack-offset");
const cosTypeHeader = response.headers.get("x-cos-meta-edgepack-type");

if (!cosOffsetHeader || !cosTypeHeader) {
return false;
}

this.signVersion = cosTypeHeader;
this.centralDirectoryOffset = Number(cosOffsetHeader);

if (this.signVersion === "v1") {
this.customBlockValueStart = this.totalSize - APK_COMMENT_LENGTH;
this.customBlockValueEnd = this.totalSize;
} else {
this.customBlockValueStart =
this.centralDirectoryOffset -
CUSTOM_BLOCK_VALUE_LENGTH -
APK_SIGNING_BLOCK_MAGIC_LENGTH -
APK_SIGNING_BLOCK_OFFSET_LENGTH;
this.customBlockValueEnd = this.centralDirectoryOffset;
}

this.rangeRelativeOffset = this.getRelativeOffset(response);

if (this.rangeRelativeOffset === null) {
return false;
}

return true;
}

async combineStreams(request) {
// Handle a single Range or a full request
let contentLength = this.totalSize;

if (this.customRange) {
const [rangeStart, rangeEnd] = this.customRange;

if (rangeStart === null && rangeEnd !== null) {
// bytes=-suffix format: the last suffix bytes
contentLength = Math.min(rangeEnd, this.totalSize);
} else if (rangeEnd !== null) {
// bytes=start-end format
contentLength = rangeEnd - rangeStart + 1;
} else if (rangeStart !== null) {
// bytes=start- format
contentLength = this.totalSize - rangeStart;
}
}

const { readable, writable } = new FixedLengthStream(contentLength);
this.handleStream(request, writable);
return readable;
}

/**
* Write data in the specified range
* Use pipeTo to optimize performance, suitable for single Range requests
* @private
*/
async _writeRangeData(request, writable, actualStart, actualEnd) {
const comment = this.customInfo;
const encoder = new TextEncoder();
const section = encoder.encode(comment);

// Header section: data before the signature block
if (actualStart < this.customBlockValueStart) {
const apkHeader = await this.apkHeaderStream(
request,
actualStart,
actualEnd
);
if (apkHeader !== null) {
try {
await apkHeader.pipeTo(writable, {
preventClose: true,
});
} catch (e) {
console.error("HEADER_STREAM_ERROR: ", e);
}
}
}

// Body section: signature block (channel information injection area)
if (
actualStart < this.customBlockValueEnd &&
(actualEnd === null || actualEnd >= this.customBlockValueStart)
) {
const apkBody = await this.apkBodyStream(
request,
section,
actualStart,
actualEnd
);
if (apkBody !== null) {
const apkBodyStream = apkBody.stream();
try {
await apkBodyStream.pipeTo(writable, {
preventClose: true,
});
} catch (e) {
console.error("BODY_STREAM_ERROR: ", e);
}
}
}

// Tail section: data after the signature block
if (actualEnd === null || actualEnd >= this.customBlockValueEnd) {
const apkTail = await this.apkTailStream(
request,
actualStart,
actualEnd
);
if (apkTail !== null) {
try {
await apkTail.pipeTo(writable, {
preventClose: true,
});
} catch (e) {
console.error("TAIL_STREAM_ERROR: ", e);
}
}
}
}

async handleStream(request, writable) {
try {
const [rangeStart, rangeEnd] = this.customRange || [0, null];

let actualStart = rangeStart;
let actualEnd = rangeEnd;

if (rangeStart === null && rangeEnd !== null) {
actualStart = Math.max(0, this.totalSize - rangeEnd);
actualEnd = this.totalSize - 1;
}

await this._writeRangeData(request, writable, actualStart, actualEnd);
} catch (err) {
console.error("HANDLE_STREAM_ERROR: ", err);
} finally {
let writer = writable.getWriter();
writer.close();
writer.releaseLock();
}
}

async apkHeaderStream(request, actualStart, actualEnd) {
const headers = new Headers(request.headers);

let headerStart = 0;
let headerEnd = this.customBlockValueStart - 1;

if (actualStart > 0) {
headerStart = Math.max(headerStart, actualStart);
}
if (actualEnd !== null) {
headerEnd = Math.min(headerEnd, actualEnd);
}

if (headerStart > headerEnd) {
return null;
}

headers.set("Range", `bytes=${headerStart}-${headerEnd}`);

// Get the part before the signature block
const headResponse = await fetch(request, {
headers: headers,
});

return headResponse.body;
}

async apkBodyStream(
request,
section = null,
actualStart = 0,
actualEnd = null
) {
const headers = new Headers(request.headers);

let bodyStart = this.customBlockValueStart;
let bodyEnd = this.customBlockValueEnd - 1;

if (actualStart > this.customBlockValueStart) {
bodyStart = Math.max(bodyStart, actualStart);
}
if (actualEnd !== null) {
bodyEnd = Math.min(bodyEnd, actualEnd);
}

if (bodyStart > bodyEnd) {
return null;
}

headers.set("Range", `bytes=${bodyStart}-${bodyEnd}`);

const middleResponse = await fetch(request, {
headers: headers,
});

const reader = middleResponse.body.getReader();

let outputBuffers = [];
try {
let handledBytes = bodyStart;
while (true) {
const result = await reader.read();

if (result.done) {
console.log("APK_BODY_STREAM_DONE");
break;
}

const startByteOffset = handledBytes;
const buffer = result.value;
handledBytes += buffer.byteLength;

// Absolute position of channel information in the signature block
const channelAbsoluteStart = this.customBlockValueStart;
const channelAbsoluteEnd = channelAbsoluteStart + section.byteLength;

// Calculate the range in the current buffer that needs to be replaced
const min = Math.max(startByteOffset, channelAbsoluteStart);
const max = Math.min(channelAbsoluteEnd, handledBytes);

if (min < max) {
const bufferStart = min - startByteOffset;
const sectionStart = min - channelAbsoluteStart;
const sectionEnd = max - channelAbsoluteStart;

const replacement = section.subarray(sectionStart, sectionEnd);

new Uint8Array(buffer).set(replacement, bufferStart);
}

outputBuffers.push(buffer);
}
} catch (err) {
console.error("APK_BODY_STREAM_ERROR: ", err);
}
return new Blob(outputBuffers);
}

async apkTailStream(request, actualStart, actualEnd) {
const headers = new Headers(request.headers);

let tailStart = this.customBlockValueEnd;
let tailEnd = this.totalSize - 1;

if (actualStart > this.customBlockValueEnd) {
tailStart = Math.max(tailStart, actualStart);
}
if (actualEnd !== null) {
tailEnd = Math.min(tailEnd, actualEnd);
}

if (tailStart > tailEnd) {
return null;
}

headers.set("Range", `bytes=${tailStart}-${tailEnd}`);

const tailResponse = await fetch(request, {
headers: headers,
});

return tailResponse.body;
}
}

async function handleEvent(event) {
const edgepack = new EdgePack();
await edgepack.handle(event);
}

addEventListener("fetch", handleEvent);
2. After deploying the function, configure the trigger rule by following the instructions in Function Management. Set the HOST value to the acceleration domain created in Step 1, as shown below:



3. Click OK to complete the trigger rule creation. When a user accesses the domain www.example.com and the file extension is .apk, the edge function is triggered to perform dynamic packaging.

Step 3: Verifying Whether the EdgeOne Edge Function Has Written Channel Information to the Android APK Package

Enter a URL with channel information in the browser, for example, http://www.example.com/v2_src.apk?comment=test, to trigger the edge function and dynamically inject the channel information into the specified location. The comment parameter is the channel parameter you defined in Creating an Edge Function for Triggering Channel Information Writing. Taking the v2-VasDolly method as an example, you can use the VasDolly multi-channel packaging tool to read the dynamically injected channel information: